Search code examples
c++memory-managementdelete-operator

Is delete[] equal to per element delete. c++


Everyone!

Lets say I'm writing the Array class and want to optimize construction

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'm wondering how to free memory correctly:

  1. delete[] data;

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


Solution

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

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

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