smart pointers and arrays

C++C++11Smart Pointers

C++ Problem Overview


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)?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

Edit: This answer was wrong, as explained by the comments below. Here's what I originally said:

> I don't think std::unique_ptr knows to call delete[]. It effectively > has an int* as a member -- when you delete an int* it's going to > delete the entire array, so in this case you're fine. > > The only purpose of the delete[] as opposed to a normal delete is that > it calls the destructors of each element in the array. For primitive > types it doesn't matter.

I'm leaving it here because I learned something -- hope others will too.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhelloworld922View Question on Stackoverflow
Solution 1 - C++Alok SaveView Answer on Stackoverflow
Solution 2 - C++Nathan MonteleoneView Answer on Stackoverflow