Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smart pointers and arrays

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

like image 315
helloworld922 Avatar asked Jul 15 '11 21:07

helloworld922


People also ask

What are pointers and arrays?

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.

What are smart pointers used for?

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.

What is the difference between pointers and smart pointers?

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.

Which is better pointer or array?

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.


2 Answers

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.

like image 104
Alok Save Avatar answered Sep 22 '22 06:09

Alok Save


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.

like image 44
Nathan Monteleone Avatar answered Sep 21 '22 06:09

Nathan Monteleone