I'm reading Section 4.2.3 Initializing Containers, Tour of C++ Second Edition.
It says:
Vector read(istream& is) { Vector v; for (double d; is>>d;) v.push_back(d); return v; }
... The way to provide
Vector
with a move constructor, so that returning a potentially huge amount of data fromread()
is cheap, is explained in §5.2.2:Vector v = read(cin); // no copy of Vector elements here
Is it guaranteed that the above expression will be copy-elided (in C++17)?
I think v
in the return is an lvalue & a local variable, so it can be copy-elided but is not guaranteed to be elided.
Am I missing something here?
Is it guaranteed that the above expression will be copy-elided (in C++17)?
I think v in the return is an lvalue & a local variable, so it can be copy-elided but is not guaranteed to be elided. Am I missing something here?
From copy_elision
Non-mandatory elision of copy/move (since C++11) operations
In a return statement, when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and which is of the same class type (ignoring cv-qualification) as the function return type. This variant of copy elision is known as NRVO, "named return value optimization".
So NRVO is not guarantied, even in C++17.
But, if not applied, move-constructor is done (See return statement for details).