Daemon
Daemon

Reputation: 1675

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() {
        // your code goes here
        MyClass* p = new MyClass[1];
        delete[] p;
        cout << "Size of class: " << sizeof(MyClass) << endl;  
        return 0;
}

Here I am overloading the new and delete operator. The strange behaviour what I observe here is if I include the destructor size passed to new operator is increased by 4 and size of MyClass is still 4 which is obvious.

The output I am getting is with destructor:
Size: 8
Size of class: 4

The output I am getting is without destructor:
Size: 4
Size of class: 4

Why is it so that inclusion of destructor increases the size?

Upvotes: 2

Views: 110

Answers (1)

David Schwartz
David Schwartz

Reputation: 182827

Think about how delete[] works. If there's no destructor, most likely all it needs to do is pass the address to free. But if there is a destructor, it has to know how many elements are in the array so it knows how many times to invoke the destructor. So some extra space is needed to hold the size of the array.

Upvotes: 5

Related Questions