Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing RVO / move construction when returning by value

Say I have an object 'foo' with a copy constructor and a move constructor, and a function

foo f() {
    foo bar;
    /* do some work */
    return bar;
}

The standard appears to state that the compiler will try to do: NRVO, return by r-value ref, return by value, fail; in that order.

Is there any way to force the compiler to never return by value, since my copy constructor is quite expensive?

like image 613
C. Broadbent Avatar asked Dec 21 '22 13:12

C. Broadbent


1 Answers

the compiler will try to do: NRVO, return by r-value ref, return by value, fail; in that order.

The wording above is imprecise and might indicate a misunderstanding on your side. The compiler can use NRVO (most will), if that is not available it will always return by value, the difference is how the returned value will be constructed. If your type has a move constructor, the compiler must use that constructor and will only fall to use a copy constructor if your type does not have a move constructor.

That is, if your type has a move constructor a compiler that used the copy constructor would not be C++11 compliant.

like image 181
David Rodríguez - dribeas Avatar answered Dec 24 '22 02:12

David Rodríguez - dribeas