Search code examples
c++auto-ptr

What is the correct way of using an auto_ptr on dynamically allocated arrays?


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.


Solution

  • 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.