ritter
ritter

Reputation: 7699

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?

Upvotes: 6

Views: 525

Answers (3)

Xeo
Xeo

Reputation: 131799

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

Upvotes: 9

Puppy
Puppy

Reputation: 146930

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

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227418

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.

Upvotes: 3

Related Questions