I can\'t figure out why the copy-constructor is not called when I try to return a local variable defined within a function. See the following simplified example:
<
The compiler optimizes away the return copy. This is known as NRVO (Named Return Value Optimization).
in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
The compiler is allowed to do this, even if the copy constructor has side effects.
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.
That is, if you give your copy/move constructors side effects, your program has multiple valid execution paths, depending on whether your compiler wants to optimize or not.