views:

213

answers:

3

How do you go about using the return value optimization?
Is there any cases where I can trust a modern compiler to use the optimization, or should I always go the safe way and return a pointer of some type/use a reference as parameter?

Is there any known cases where the return value optimization cant be made?, Seems to me that the return value optimization would be fairly easy for a compiler to perform.

+2  A: 

To have the best chance that it occurs, you can return an object constructed directly in the return statement [can anyone remember the name for this idiom - I've forgotten it]:

Foo f() {
    ....
    return Foo( ... );
}

But as with all optimisations, the compiler can always choose not to do it. And at the end of the day, if you need to return a value thee is no alternative to trusting the compiler - pointers and references won't cut it.

anon
+6  A: 

Whenever compiler optimizations are enabled (and in most compilers, even when optimizations are disabled), RVO will take place. NRVO is slightly less common, but most compilers will perform this optimization as well, at least when optimizations are enabled.

You're right, the optimization is fairly easy for a compiler to perform, which is why compilers almost always do it. The only cases where it "can't be made" are the ones where the optimization doesn't apply: RVO only applies when you return an unnamed temporary. If you want to return a named local variable, NRVO applies instead, and while it is slightly more complex for a compiler to implement, it's doable, and modern compilers have no problem with it.

jalf
Especially, if you have 2 named variables and pick up the one to return at runtime, obviously the compiler cannot perform NRVO :)
Matthieu M.
Matthieu, I assume the same goes for two unnamed exits? (ie, "if (...) return A() else return B();"
Viktor Sehr
@Viktor: No - that's RVO, not **N**RVO. Only one of them will be constructed. So both code paths can use the same memory, which is the memory reserved for the return value. That's the essence of RVO: directly create the return value in the memory reserved for it.
MSalters
Matthieu: no, NRVO may still be possible if there are two variables that may be returned. Sometimes my functions have an "if" statement. In one branch I construct a named value, manipulate it and return it; in the other branch I do the same thing but maybe use a different constructor. There's no reason the compiler couldn't optimize that, but I'm pretty sure mine can't (Visual C++).
Qwertie