2

Let's say I'm using std::auto_ptr in my code.*

Is there any danger in returning an std::auto_ptr object?
i.e. Could it result in a memory leak, undefined behavior, etc.? or is it a safe use of std::auto_ptr?

*I'm not asking if there is a better substitute (like shared_ptr); I'm specifically asking about the pitfalls of returning auto_ptr itself.

user541686
  • 205,094
  • 128
  • 528
  • 886
  • It's not wrong and it's not error-prone. `auto_ptr` works perfectly for that case. – Jonathan Wakely Jul 01 '13 at 08:31
  • @JonathanWakely: Cool, thanks, just wanted to make sure I'm not missing anything (a direct answer didn't come up in searches). – user541686 Jul 01 '13 at 08:36
  • 2
    Although you're right about this functionality of auto_ptr, bear in mind that it is deprecated in C++11 and `unique_ptr` is preferred instead. – the_mandrill Jul 01 '13 at 08:38
  • @the_mandrill: Yup I'm aware, it's still useful though. Namely when trying to stay backwards-compatible, as well as when the result might be used in `boost::ptr_vector::push_back` or whatever. – user541686 Jul 01 '13 at 08:41
  • 1
    This is exactly what `auto_ptr` was designed for. The original proposal was for something more like `scoped_ptr`, and some one (I think it was Bill Gibbons) pointed out that they'd found the transfer of ownership semantics very useful for things like factory methods. The result was `auto_ptr`. – James Kanze Jul 01 '13 at 08:48

1 Answers1

4

In general it's safe and can lead to more robust code. It should not lead to a memory leak since the memory pointed to is automatic deleted.

But there are some cases where you have to take care:

  • Copies of auto_ptr are not equal!
  • Construction of one auto_ptr from another will release the object the first pointer was pointing to

Please see here:

  1. http://www.gotw.ca/publications/using_auto_ptr_effectively.htm
  2. http://www.cprogramming.com/tutorial/auto_ptr.html

The auto_ptr template class is designed to help manage memory in a semi-automatic way and prevent memory leaks when unexpected events such as exceptions would otherwise have caused the normal cleanup code to be skipped.

(quoted from (2))

David G
  • 94,763
  • 41
  • 167
  • 253
ollo
  • 24,797
  • 14
  • 106
  • 155