Is it possible to write C++ code where we rely on the return value optimization (RVO) when possible, but fall back on move semantics when not? For example, the following code c
Yes, there is. Don't return the result of a ternary operator; use if
/else
instead. When you return a local variable directly, move semantics are used when possible. However, in your case you're not returning a local directly -- you're returning the result of an expression.
If you change your function to read like this:
Foo f(bool b) {
Foo x;
Foo y;
if (b) { return x; }
return y;
}
Then you should note that your move constructor is called instead of your copy constructor.
If you stick to returning a single local value per return statement then move semantics will be used if supported by the type.
If you don't like this approach then I would suggest that you stick with std::move
. You may not like it, but you have to pick your poison -- the language is the way that it is.