Home > Software design >  Will the compiler ever use the move constructor to move a named variable that is about to go out of
Will the compiler ever use the move constructor to move a named variable that is about to go out of

Time:09-07

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?

CodePudding user response:

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.

CodePudding user response:

The compiler is allowed to do any optimization, that does not influence the program's side effects. This is called the as-if rule. There are very few exceptions to that rule, from which copy elision is one. The rules for copy elision don't apply in your example, thus the compiler is not allowed to change the side effects of the program by optimizing. Your program will behave as if the copy constructor is called.

  • Related