Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do compilers automatically use move semantics when a movable object is used for the last time?

People also ask

When should I use move semantics?

Move semantics allows you to avoid unnecessary copies when working with temporary objects that are about to evaporate, and whose resources can safely be taken from that temporary object and used by another.

How are Move semantics implemented?

Move semantics aim to avoid the copying of data from temporary objects by instead stealing the memory location of where the object resides. This behaviour is implemented through the use of a move constructor and move assignment operator that act only on rvalue references.

Are move semantics important?

Move semantics allows an object, under certain conditions, to take ownership of some other object's external resources. This is important in two ways: Turning expensive copies into cheap moves. See my first answer for an example.


Is this optimization allowed by the C++0x Standard?

No.

Do the compilers employ it? Even in complex cases, i.e. the function consists from more than one line?

No.

How reliable is this optimization, i.e. can I expect the compiler to utilize it as much as I expect the compiler to apply Return Value Optimization?

You should decorate A(const A&) and A(A&&) with print statements and run test cases of interest to you. Don't forget to test lvalue arguments if those use cases are part of your design.

The correct answers will depend upon how expensive the copy and move of A are,how many arguments Object::value actually has, and how much code repetition you're willing to put up with.

Finally, be very suspicious of any guideline that contains words like "always" or "everywhere". E.g. I use goto every once in a while. But other programmers have words like "never" associated with goto. But every once in a while, you can't beat a goto for both speed and clarity.

There will be times you should favor a pair of foo(const A&) foo(A&&) over foo(A). And times you won't. Your experiments with decorated copy and move members will guide you.