Auto_ptr pointing to a dynamic array

In my code, I allocate an integer array using new. After that, I wrap this pointer with auto_ptr. I know that auto_ptr calls its destructor automatically. Since my auto_ptr points to an array (allocated with new), will the array be deleted along with auto_ptr or it will 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; } 
+4
source share
3 answers

The array will not be deleted correctly. auto_ptr uses delete contained_item; . For the array, use delete [] contained_item; instead delete [] contained_item; . The result is undefined behavior.

As James McNellis said, you really want std::vector here - no new , no auto_ptr and don't worry.

+9
source

You cannot use std :: auto_ptr to process dynamic arrays, since it cannot know how to distinguish between deletion and deletion [].

Also, auto_ptr deprecated, in C ++ 11 you can use std::unique_ptr with:

 int *array = new int[2]; std::unique_ptr<int[]> pointer(array); 
+9
source

As others have said, auto_ptr is the wrong thing, it is better to use std :: vector. But you can also use boost :: scoped_array. But note that you want to reset at the time of creation, otherwise you could use delete. pointer.reset (new int [2]);

or better yet, like this boost :: scoped_array arr (new int [2]);

It also makes no sense to create a static pointer std :: auto_ptr; on a global scale. This means that it will only be deleted when the program exists, which happens anyway, even if you skip memory.

+1
source

Source: https://habr.com/ru/post/1491779/


All Articles