Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

move semantics - not with temporary objects

27 views
Skip to first unread message

porp...@gmail.com

unread,
Nov 11, 2017, 6:10:07 AM11/11/17
to
Hi,
It is common that move semantics is closely related to temporary objects.
The following example shows that it isn't

MyClass {...};

MyClass fun ( void ) {
MyClass myObj;
return myObj;
}

int main ( void ) {
MyClass myObj;
myObj = fun();
return 0;
}

When I build it with "g++ -O3" the temporary object is never created inside fun(). Doesn't matter whether I create move constructor and move assignment operator inside MyClass or not. I think that in this example move semantics has got nothing to do with temporary objects. As the result saying that move semantics is closely related with temporary objects is wrong.
In the example above the compiler just knows that myObj inside fun() is going to evaporate and this is why it uses move assignment operator to steal the resources from it.

Please let me know whether I'm right or not.

thanks in advance

Alf P. Steinbach

unread,
Nov 11, 2017, 7:52:29 AM11/11/17
to
This is commonly known as Return Value Optimization, or RVO, where each
call site passes the address of where the function result should be
constructed.

RVO is one kind of copy construction elision.

However, in C++11 and later it's not just copy constructor invocations
that can be elided: also move constructor invocations can be elided,
which, depending on MyClass, is most probably what happens here.



Cheers & hth.,

- Alf

Chris Vine

unread,
Nov 11, 2017, 9:17:05 AM11/11/17
to
You have been told about return value optimization in a separate answer.
RVO is one of the few occasions where the C++ standard permits
copy/move constructors to be elided for non-trivial types. Move
construction doesn't occur in your example.

On your more general point about move semantics and temporaries, it
would be more correct to say that move semantics are associated with
rvalues, because rvalues bind to rvalue references. An unnamed object
(temporary) is a prvalue and is one example of an rvalue. Another is an
lvalue cast to rvalue using std::move (that produces an xvalue, which
is another category of rvalue).

This will give you more information:
http://en.cppreference.com/w/cpp/language/value_category

Chris




0 new messages