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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top