Return auto_ptr payload by value in C++ from function
-
30-04-2021 - |
Question
Does C++ standard guarantee that here would be no crash when returning auto_ptr
's payload by value from the function:
class Foo { ... };
std::auto_ptr<Foo> createFoo() {
return std::auto_ptr<Foo>(new Foo(...));
}
...
Foo getFoo() {
std::auto_ptr<Foo> foo(createFoo());
return *foo; /// would be here a crash?
}
/// main
const Foo& foo(getFoo());
What's going here accordingly to the standard: *foo
is copied, then foo
is destroyed and finally return
is performed? Or there is an another order of steps?
I tested this example with GCC and there is no crash but I am not sure that it would work with another compilers.
Solution
It is very strange code, but, yes - it is guaranteed. There is no RVO, or move semantics, so it should be ok.
OTHER TIPS
As getFoo
returns by value, it creates (yet another) copy of the Foo
object. After that, it doesn't matter that the original object is deleted by the auto_ptr
.
Rather strange code though, to use an auto_ptr
and then create a copy anyway.