Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Your code will never return by copy if foo has a working move constructor.

You can also make use an out-parameter instead of returning:

void f(foo& bar) { ... }

But in practice all compilers will do NVRO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top