-1

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.

barankin
  • 1,853
  • 2
  • 12
  • 16

2 Answers2

2

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
1

It is very strange code, but, yes - it is guaranteed. There is no RVO, or move semantics, so it should be ok.

innochenti
  • 1,093
  • 2
  • 8
  • 23