My code is as follows. Why () makes RVO fail?
A fn() {
A a{};
return (a); // move constructor of class A works
return a; // RVO works
}
int main() {
A a = fn();
return 0;
}
This is NRVO, not RVO.
Here is the rule which allows NRVO (class.copy/31):
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 or catch-clause parameter) with the same cv- unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
As you can see, in the case of (a)
, the expression is not a name (because of the added parenthesis), so NRVO is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With