tags:

views:

162

answers:

5

If i use auto_ptr to hold a pointer to a dynamically allocated array, when the auto_ptr gets killed it will use a plain delete operation and not delete[] thus not deleting my allocated array.

How can i (properly) use auto_ptr on dynamically allocated arrays?

If this is not possible, is there another smart pointer alternative for dynamically allocated arrays?

Thanks in advance.

+4  A: 

boost::shared_array is what your looking for.

EDIT:

If you want to avoid the use of boost I would recommend just using std::vector they are array's underneath and there is no need to worry about memory allocation. Actually this is a better solution than shared_array anyway.

Since you indicate that you wanted to use auto_ptr then you don't need the reference counting and ownership model of shared_array. So just use a std::vector as they are tailored to replace dynamically allocated arrays which is really what you are trying to manage with the use of auto_ptr.

radman
Can using boost be avoided?
LoudNPossiblyRight
A: 

If you want to do it yourself (i.e. not use boost) then wrap the dynamic array in a class first. Have the class's destructor call delete[]. Then the auto_ptr<Wrapper> can call delete on the class and the memory will be deallocated properly.

Duracell
A: 

The correct way of using auto_ptr (with a dynamically allocated array or anything else) is to use something else instead. Either boost::shared_array or perhaps shared_ptr> or shared_ptr> from TR1 in your case. In the general case shared_ptr or unique_ptr are smart pointers that are actually smart. Stop using auto_ptr.

Kate Gregory
That's just not true. auto_ptr has valid use cases. Admittedly that are not easy for the novice to understand but a blanket you should not use them is just plain bad advice.
Martin York
if you have shared_ptr and unique_ptr you are done with figuring whether auto_ptr is going to be safe in this container etc. A tool you need to think carefully about using is a tool I happily abandon when I get a better option; and shared_ptr and unique_ptr are better options.
Kate Gregory
+8  A: 

You don't. std::auto_ptr isn't meant to be used with arrays.

Avoid using new[] and delete[]. Use std::vector instead. This is Stroustrup's recommendation too.

If you're using an array because you need to pass it to code that expects a pointer, you can simply pass the address of a vector's first element instead. For example:

std::vector<char> buf(size);
fgets(&buf[0], buf.size(), stdin);
jamesdlin
A: 

The proper boost smart pointer in this case is boost::scoped_array, not the more famous boost::shared_array, because std::auto_ptr is a sole ownership pointer. The opposite of a shared ownership pointer. In C++0x, the correct pointer is std::unique_ptr, which will call delete[] if it is pointing at an array, or delete if it's pointing at a single object.

Cubbi