Why do C ++ destructors increase the size of the object in which they are located?

I know this may sound like a strange question, but I'm just wondering if a class in C ++ weighs more than a structure with the same data fields, and this one thing I could not find the answer for ... <w > Consider this:

struct SomeStruct { int a; int b; }; class SomeClass { public: SomeClass():a(0),b(0){} private: int a; int b; }; int main() { std::cout<<sizeof(SomeStruct)<<std::endl; // output is 8 std::cout<<sizeof(SomeClass)<<std::endl; // output is 8 } 

But now let's see what happens when I add a destructor to SomeClass:

 struct SomeStruct { int a; int b; }; class SomeClass { public: SomeClass():a(0),b(0){} virtual ~SomeClass(){} private: int a; int b; }; int main() { std::cout<<sizeof(SomeStruct)<<std::endl; // output is 8 bytes std::cout<<sizeof(SomeClass)<<std::endl; // output is 16 bytes! } 

Why does SomeClass need another 8 bytes for the destructor?

+7
c ++ destructor
source share
3 answers

The increase in size is due to virtual . If you do not make a virtual destructor, you will not see an increase in size.

So, this is not a destructor that makes your type bigger, but rather adds a virtual function that does this.

8 extra bytes is a pointer to a virtual table ( vtable ) for the class you are using. As noted in the comments, this is a โ€œone-timeโ€ cost. Adding one virtual function to the class leads to such a cost, but you do not see this cost with additional virtual functions.

Edit:

The extra size in the class will depend on whether it is compiled as a 32-bit or 64-bit program. A link to a virtual table occupies 4 additional 32-bit and 8 additional bytes on a 64-bit platform.

+17
source share

It is not a fact that you added a destructor. It is the fact that you have added a virtual method (additional virtual methods will not have additional costs for each instance). Most (all?) C ++ implementations use a table of virtual function pointers to enable dynamic dispatch, and this requires that a pointer to the corresponding table be stored in each object. This pointer-virtual table is an extra space for every object that you see.

+4
source share

When you declare a destructor as virtual, the compiler automatically adds a vtable pointer as a member of your class. This is necessary so that it can find the address of all class destructors derived from yours.

This new member (which you cannot access trivially, and should not) is added to your class and thus increases its size by the size of a trivial raw pointer, which usually has the same size as int, but may depend from your architecture.

0
source share

All Articles