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)?
Difference between Arrays and pointers. An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable. An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.
Smart pointers are used to make sure that an object is deleted if it is no longer used (referenced). The unique_ptr<> template holds a pointer to an object and deletes this object when the unique_ptr<> object is deleted.
A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.
Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.
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_ptr
by:
std::unique_ptr<int[]> my_array(new int[5]);
This is called as Partial Specialization of the unique_ptr
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With