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?