Parameter elision
suggest changeWhen you pass an argument to a function, and the argument is a prvalue expression of the function’s parameter type, and this type is not a reference, then the prvalue’s construction can be elided.
void func(std::string str) { ... }
func(std::string("foo"));
This says to create a temporary string
, then move it into the function parameter str
. Copy elision permits this expression to directly create the object in str
, rather than using a temporary+move.
This is a useful optimization for cases where a constructor is declared explicit
. For example, we could have written the above as func("foo")
, but only because string
has an implicit constructor that converts from a const char*
to a string
. If that constructor was explicit
, we would be forced to use a temporary to call the explicit
constructor. Copy elision saves us from having to do a needless copy/move.