Is the copy constructor always called when returning by value in C++ [duplicate]

No. The compiler is allowed to elide the call to the copy constructor in some cases. Look up RVO (Return Value Optimization) and NRVO (Named Return Value Optimization). Also, since C++17, this optimization is guaranteed in some cases.

Additionally, if the returned type is movable, the compiler may do a move rather than a copy in some cases.

Leave a Comment