When a function returns a class type object, RVO is allowed under only two circumstances:
- The returned expression is the name of a non-volatile automatic object, or
- the returned expression refers to a temporary object which has not been bounded to a reference.
So your code won't trigger RVO.
If the Foo
object is declared with automatic storage, a compiler is allowed to do RVO:
Foo bar()
{
Foo foo;
return foo; // foo can be constructed directly as the returned object
}
If for some reason you have to create the object with new
and want to eliminate the copy operation, you may use std::move
, which will change an expression into an rvalue:
Foo bar()
{
std::unique_ptr<Foo> ptr(new Foo);
return std::move(*ptr); // No deep copy if Foo implements
// its own move constructor
}