mercredi 4 mai 2016

Using std::move inside a move constructor

This answer writes a move constructor like this:

dumb_array(dumb_array&& other)
        : dumb_array() // initialize via default constructor, C++11 only
    {
        swap(*this, other);
    }

Note: this swap is a custom swap also defined on the class, not std::swap.

This answer suggests that use of std::move:

you should only call std::move where appropriate, but this is were personal preferences come in.

I just watched a Scott Meyers talk on move semantics where he stated that an rvalue reference as a function parameter is turned back into an lvalue by virtue of the fact that it is now named, and therefore std::move is necessary once again turn it back into an rvalue.

In other words, the code above may very well not be doing a move operation, and that, unlike the quote above, use of std::move in such contexts is not about personal preference but about actually gaining benefits of move semantics.

Is it accurate to say then that if std::move is not explicitly used inside a move constructor or a move assignment operator, moving is probably not actually happening, and instead a copy is being done?

Aucun commentaire:

Enregistrer un commentaire