سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top