consider function void foo() and class myclass
class myclass { /* some data members, including pointers, and a move constructor */ };
void foo()
{
myclass myvar = myclass(...); // foo() allocates space on the stack for sdlv
// then passes address in %rdi to constructor
/* myvar is used a few times */
myclass myvar_copy = myvar; // myvar used for the last time
return;
}
myvar is an lvalue, but when it is used for the final time, it might as well be a reference to a rvalue (&&). A C++ compiler will detect a typical && (like x * y) by recognizing that (x * y) is a temporary object. Will a C++ compiler (say gcc) intelligently know to use a move constructor in the example above too?
myclass myvar_copy = myvar;
is copy initialization where myvar
is an lvalue. The copy constructor has a parameter of type const myclass&
and the move constructor has a parameter of type myclass&&
.
Now, since the argument that we're passing is myvar
which is an lvalue only the copy constructor can be used since the move constructor parameter is myclass&&
which cannot be bound to an lvalue.