Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 move constructor with side effects

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?

like image 570
ritter Avatar asked Aug 03 '12 08:08

ritter


People also ask

Is move constructor faster than copy constructor?

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.

Why should move constructor be Noexcept?

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)

Are move constructors automatically generated?

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.

What is the point of a move constructor?

A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying.


3 Answers

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. [...]

like image 129
Xeo Avatar answered Oct 18 '22 07:10

Xeo


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.

like image 25
juanchopanza Avatar answered Oct 18 '22 06:10

juanchopanza


Elision is defined identically for both copy and move. The Standard does not have any specific wording for move, because they're defined identically.

like image 25
Puppy Avatar answered Oct 18 '22 07:10

Puppy