Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return value optimization does not work when return ()

Tags:

c++

c++11

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;
}
like image 812
cosimoth Avatar asked Mar 27 '20 12:03

cosimoth


1 Answers

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.

like image 177
geza Avatar answered Nov 06 '22 13:11

geza