~Nit: If the compiler doesn’t elide this, the const will force an extra copy: https://stackoverflow.com/questions/25784544/will-returning-a-const-object-from-a-function-prevent-move-construction-from-out/25786015~
Edit: TIL. Looks like this is “permitted” to be elided according to the c++17 final working draft: (emphasis mine)
This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
- (1.1) 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 parameter or a variable introduced by the exception-declaration of a handler (18.3)) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call’s return object
But “required” according to cppreference:
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
- In a return statement, when the operand is a prvalue of the same class type (ignoring cv-qualification) as the function return type
So.. 🤷
Maybe that draft wasn’t final wrt elision or maybe cppreference is wrong. It really doesn’t matter either way :)