c++ - Size of a class increases if destructor is included -
class myclass { int data; public: myclass() : data(0) { /*cout << "ctor" << endl;*/} void* operator new(size_t sz) { cout << "size in new: " << sz << endl; void* s = malloc(sz); return s; } void* operator new[] (size_t sz) { cout << "size: " << sz << endl; void* s = malloc(sz); return s; } void operator delete(void* p) { free(p); } void operator delete[](void* p) { free(p); } ~myclass() {} }; int main() { // code goes here myclass* p = new myclass[1]; delete[] p; cout << "size of class: " << sizeof(myclass) << endl; return 0; }
here overloading new , delete operator. strange behaviour observe here if include destructor size passed new operator increased 4 , size of myclass still 4 obvious.
the output getting destructor:
size: 8
size of class: 4
the output getting without destructor:
size: 4
size of class: 4
why inclusion of destructor increases size?
think how delete[]
works. if there's no destructor, needs pass address free
. if there destructor, has know how many elements in array knows how many times invoke destructor. space needed hold size of array.
Comments
Post a Comment