Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto_ptr pointing to a dynamic array

Tags:

c++

auto-ptr

In my code, I am allocating an integer array using new. After that I am wrapping this pointer to an auto_ptr. I know that the auto_ptr call its destructor automatically. Since my auto_ptr is pointing to an array (allocated using new), Will the array get deleted along with auto_ptr or will it cause a memory leak. Here is my sample code.

std::auto_ptr<int> pointer;

void function()
{
  int *array = new int[2];
  array[0] = 10;
  array[1] = 20;

  pointer.reset((int*) array);
}

int _tmain(int argc, _TCHAR* argv[])
{

    function();
return 0;
}
like image 747
Aneesh Narayanan Avatar asked Dec 02 '22 18:12

Aneesh Narayanan


1 Answers

The array will not be deleted correctly. auto_ptr uses delete contained_item;. For an array it would need to use delete [] contained_item; instead. The result is undefined behavior.

As James McNellis said, you really want std::vector here -- no new, no auto_ptr and no worries.

like image 181
Jerry Coffin Avatar answered Dec 11 '22 22:12

Jerry Coffin