C ++ operator sizeof before and after extension

Now I am testing the result of the C ++ sizeof operator:

 class S{}; class A:public S{ virtual void fun()=0; }; class B{}; class C : public B,public A {}; int main(){ cout<<sizeof(A)<<endl;// result is 4 cout<<sizeof(C)<<endl;// result is 8 } 

But if I remove the extension of class S:

 class A{ virtual void fun()=0; }; class B{}; class C : public B,public A{}; int main(){ cout<<sizeof(A)<<endl;// result is 4 cout<<sizeof(C)<<endl;// result is 4 } 

Can someone explain the different sizeof(C) results in these two examples? Class S is just an empty class (I know sizeof(S) == 1 ), so why does it matter if the base class A ? Especially since it does not matter for sizeof(A) , only for sizeof(C) ?

+6
source share
2 answers

It seems that VS cannot handle the situation when there is more than one empty base class. In your first example, theres is one empty base class, and in the second, two. For example, in my field, this code compiled in VS2013:

 #include <iostream> class B1 {}; class B2 {}; class B3 {}; class B4 {}; class B5 {}; class B6 {}; class C1 : B1 {}; class C2 : B1, B2 {}; class C3 : B1, B2, B3 {}; class C4 : B1, B2, B3, B4 {}; class C5 : B1, B2, B3, B4, B5 {}; class C6 : B1, B2, B3, B4, B5, B6 {}; int main() { std::cout << sizeof(C1) << ' ' << sizeof(C2) << ' ' << sizeof(C3) << ' ' << sizeof(C4) << ' ' << sizeof(C5) << ' ' << sizeof(C6) << std::endl; } 

exits

 1 1 2 3 4 5 

So far, both clang and gcc output are 1 1 1 1 1 1 .

But this behavior is still standard, since the standard does not oblige the implementation to optimize empty base classes.

+3
source

In Multiple Inheritance, Visual Studio seems to reserve at least 1 byte for each empty class.

With a default alignment of 4 bytes, this results in class C being 8 bytes.

But it can serve a purpose.

With multiple inheritance, class C is as follows:

B Part

S part

A part

C Part

Reservation allows you to get different identities for parts as follows:

 C c1; printf("address of S part %ld\n",static_cast<S*> (&c1)); // prints 4651208 printf("address of B part %ld\n",static_cast<B*> (&c1)); // prints 4651209 with one byte alignment 
+1
source

Source: https://habr.com/ru/post/976426/


All Articles