In C++ one cannot rely on the copy constructor being called from a return statement because of a special clause in the standard that allows a compiler to omit a call to the copy constructor resulting from a return statement, even if the copy constructor has side effects. Thus, it is bad style to write a copy constructor that does something else than just copy constructing the instance.
Are there similar statements in the C++11 standard that allow the compiler to eliminate a call to the move constructor under certain circumstances - and if so, what are those circumstances?
It's faster because moving allows the source to be left in a invalid state, so you can steal it's resources. For example, if a object holds a pointer to a large block of allocated memory, a move can simply steal the pointer while a copy must allocate its own memory and copy the whole memory block.
noexcept is nice for two reasons: The compiler can optimize a little better because it doesn't need to emit any code for unwinding a call stack in case of an exception, and. It leads to incredible performance differences at runtime for std::vector (and other containers, too)
If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.
A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying.
Copy-elision applies just the same to move construction, it's the exact same clause and both the elision of copy construction and move construction is collectively called "copy-elision".
§12.8 [class.copy] p31
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. [...]
When copy elision is allowed, no copying will be performed, so there will be no call to the move copy constructor, even if the object is movable. So copy elision wins over move, and you cannot be certain (at least not in a portable way) when it will take place. So this is one scenario when side effects on move copy construction would be a bad idea.
Elision is defined identically for both copy and move. The Standard does not have any specific wording for move, because they're defined identically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With