smart pointers and arrays

helloworld922 picture helloworld922 · Jul 15, 2011 · Viewed 32.6k times · Source

How do smart pointers handle arrays? For example,

void function(void)
{
    std::unique_ptr<int> my_array(new int[5]);
}

When my_array goes out of scope and gets destructed, does the entire integer array get re-claimed? Is only the first element of the array reclaimed? Or is there something else going on (such as undefined behavior)?

Answer

Alok Save picture Alok Save · Jul 15, 2011

It will call delete[] and hence the entire array will be reclaimed but I believe you need to indicate that you are using an array form of unique_ptrby:

std::unique_ptr<int[]> my_array(new int[5]);

This is called as Partial Specialization of the unique_ptr.