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?
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.
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