Marco A.
Marco A.

Reputation: 43662

auto_ptr, immediate get() and release() - is it useful?

I'm working on someone else's code that contains lots of statements like this

std::auto_ptr<ObjectA> smartptr(new ObjectA(this));
objects_list.push_back(smartptr.get());
smartptr.release();

Is this even useful? Is there some practical reason to use a smart pointer here instead of just writing

objects_list.push_back(new ObjectA(this));

Upvotes: 5

Views: 531

Answers (4)

Mike Seymour
Mike Seymour

Reputation: 254471

It provides exception safety. In the first example, the allocated object will be deleted if push_back fails; in the second example, it will leak.

Note that, since 2011, auto_ptr is deprecated in favour of unique_ptr. That has the advantage that it can be stored in the vector, relieving you of the burden of manually deleting the objects when removing them from the vector.

Upvotes: 1

vinod
vinod

Reputation: 132

Auto_ptr is useful to handle memory leakage.Please find below link for more info on auto pointer.

http://www.codeproject.com/Articles/23670/auto_ptr-and-its-usage

Upvotes: 0

syam
syam

Reputation: 15069

objects_list.push_back(new ObjectA(this));

This can leak memory. Let's see what happens when we break it down:

  • new ObjectA(this) is allocated
  • push_back is then called

However, push_back can throw and if it does, your new ObjectA is leaked.

The auto_ptr code you showed us solves this problem: if push_back throws then the pointer is still owned by auto_ptr and no leak happens.


The real solution would be to store smart pointers directly in the container instead of naked pointers (because naked pointers in containers are a headache when it comes to ensuring the objects are correctly deleted).

Unfortunately with C++03 (which is where auto_ptr comes from, it's been deprecated in C++11) this is not possible to store auto_ptr in containers (the pattern is badly broken). One could store boost::shared_ptr in containers, or switch to C++11 and store either unique_ptr or shared_ptr.

Upvotes: 14

Benjamin Bannier
Benjamin Bannier

Reputation: 58594

The idea was probably to guard against memory leaks in case the vector's push_back throws. This might happen if the vectors needs to be relocated and fails to allocate more memory.

Upvotes: 2

Related Questions