See the following code:
Class operatornewcls {PRIVATE: // Enum {SZ = 10}; int arr [SZ]; public:/* after the Destructor is defined, the value of sizeof (operatornewcls) has not changed, ** but the value of new operatornewcls [size] is equal to (sizeof (operatornewcls) * size + 4 ), ** because the length size of the array is unknown in new operatornewcls [size] [-1. * ** If no destructor is defined, ** the value of new operatornewcls [size] is equal to sizeof (operatornewcls) * size */~ Operatornewcls () {}// this function must be public and static, although it does not display the specified staticvoid * operator new [] (size_t size) {cout <"operator [], size =" <size <Endl; return malloc (size) ;}; void test43 () {int size = 25; cout <"sizeof (operatornewcls) =" <sizeof (operatornewcls) <Endl; int * arr = (int *) New operatornewcls [size]; for (INT I =-1; I <size; ++ I) {cout <"arr [" <I <"] =" <arr [I] <"\ t" <Endl ;}}
The execution result is as follows:
Comment out operatornewcls destructor ~ After operatornewcls (), the execution result is as follows:
The difference is the length of the ARR array operatornewcls: After the Destructor is defined, the length is 1004 bytes, And the ARR [-1] is the number of array elements 25. After the Destructor is commented, the length is 1000 bytes, and ARR [-1] is a random number.
Why does the array length need to be stored after the Destructor is defined?
It may be because, after the Destructor is defined, the user needs to control the release of the heap memory. Therefore, each object in the logarithm group needs to call the Destructor one by one ", therefore, you need to store the number of array elements.
If you do not define the destructor, it means that the user does not control the release of the "heap memory", so there is no need to call the Destructor one by one, so there is no need to store the number of array elements.