-6

Does the compiler always call a copy constructor when it returns an object by value in C++?

sepp2k
  • 363,768
  • 54
  • 674
  • 675

1 Answers1

1

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.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70