Is delete [] equal to delete an item. C ++

Everything!

Suppose I write an Array class and want to optimize the design

data = reinterpret_cast<T*>(new char[sizeof (T) * size]); for ( int i = 0; i < size; ++i ) { new(&data[i]) T(some_value); } 

And now I wonder how to free memory correctly:

  • delete[] data;

  • for ( int i = 0; i < size; ++i ) { data_[i].~T (); }

+5
source share
3 answers

The expression delete [] data must match the new T [] that created the array on the heap, so T is the data type * . Otherwise, the program behavior is undefined (5.3.5).

In your example, the data type and * data are unknown. If T is not char , the behavior is undefined.

You should not call delete [] data even after calling the destructors in a loop. It would be better to call delete [] reinterpret_cast <char *> (data) to avoid undefined behavior. Before freeing memory, type T destructors must be called.

+2
source

You need to first call the destructors before the delete data.

 // First step for ( int i = 0; i < size; ++i ) { data_[i].~T(); } // Second step delete [] data; 
+1
source
 // First, you must call the destructors, so that objects will be destroyed for ( int i = 0; i < size; ++i ) { data_[i].~T (); } // Then, deallocate memory from the heap. delete[] data; 
0
source

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


All Articles