1

Look at the program below:

#include <iostream>;

using namespace std;

class T 
{
public:
    int a;
    T() {a = 10; cout << "constructor" << endl;}
    ~T() {cout << "destructor" << endl;}
};


int main()
{
    T * ptr1 = new T;
    cout << hex << ptr1 << endl;
    delete ptr1;
    cout << "=======" << endl;

    T * ptr2 = new T[3];
    cout << hex << ptr2 << endl;
    delete [] ptr2;

    return 0;
}

I am really confused that how could delete [] ptr2 know that there are three elements of T and free all these three elements' memory, I think ptr2 only holds the first element's address. What is the mechanism of delete[], does ptr2 holds some other information, like the size of the allocated elements?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
imsrch
  • 1,152
  • 2
  • 11
  • 24
  • It's an implementation detail - it could vary from a trailing marked element or the size of the array being written right before the array, or even voodoo. – Luchian Grigore May 13 '13 at 14:13
  • see C++ FAQ: http://www.parashift.com/c%2B%2B-faq-lite/num-elems-in-new-array.html – taocp May 13 '13 at 14:17

0 Answers0