[英]where did my 4 bytes go?
#include <iostream>
#include <cstdlib>
using std::cout;
class A
{
public :
A() { cout << "A()" << this << "\n";}
~A() { cout << "~A()" << this << "\n";}
//void func() { }
virtual void debug(int a) { cout << "A::debug";}
private :
int a;
};
class A1 : public A
{
public :
A1() { cout << "A1()"<< this << "\n";}
~A1() { cout << "~A1()"<< this << "\n";}
private :
int a1;
};
class A2 : public A
{
public :
A2() { cout << "A2()"<< this << "\n";}
~A2() { cout << "~A2()"<< this << "\n";}
private :
int a2;
};
class B : public A1, public A2
{
public :
B() { cout << "B()"<< this << "\n";}
~B() { cout << "~B()"<< this << "\n";}
void debug() { cout << "B::debug()"; }
private :
int a3;
};
int main()
{
cout << "sizeof(int)" << sizeof(int) << "\n";
cout << "sizeof(void*)" << sizeof(void*) << "\n";
cout << "sizeof(A): " << sizeof(A) << "\n";
cout << "sizeof(A1): " << sizeof(A1) << "\n";
cout << "sizeof(A2): " << sizeof(A2) << "\n";
cout << "sizeof(B): " << sizeof(B) << "\n";
B b;
b.debug();
}
output : 输出:
sizeof(int)4
sizeof(void*)4
sizeof(A): 8
sizeof(A1): 12
sizeof(A2): 12
**sizeof(B): 28**
A()0x28fef4
A1()0x28fef4
**A()0x28ff00**
A2()0x28ff00
B()0x28fef4
B::debug()~B()0x28fef4
~A2()0x28ff00
~A()0x28ff00
~A1()0x28fef4
~A()0x28fef4
Both A1 and A2 are 4(vtbl) + 4(A'sint) + 4(respective int) = 12 bytes but B is 28 bytes I know its not guaranteed but what could be the possible use of those 4 bytes...I dont see any padding issues ? A1和A2都是4(vtbl)+ 4(A'sint)+4(相应的int)= 12个字节但是B是28个字节我知道它不能保证但是可能使用这4个字节......我没有看到任何填充问题? Can anyone point out what am I missing ?
任何人都可以指出我错过了什么?
sizeof(A): 8
The type A
has a member of type int
which in your platform is 4 bytes. 类型
A
有一个int
类型的成员,在你的平台中是4个字节。 It also has a virtual function, which means that a vptr
(virtual table pointer) is allocated for each object of your class, the size of it is another 4 bytes. 它还有一个虚函数,这意味着为类的每个对象分配一个
vptr
(虚拟表指针),它的大小是另外4个字节。
**sizeof(B): 28**
B
contains one object of type A1
(12 bytes), and an object of type A2
(another 12 bytes) and it adds another int
for a total of 12+12+4 = 28
bytes. B
包含一个类型为A1
对象(12个字节)和一个类型为A2
的对象(另外12个字节),它添加另一个int
,总共12+12+4 = 28
个字节。 This is quite straightforward. 这很简单。
machine word size alignment of data items within structures. 结构中数据项的机器字大小对齐。
See structure packing for more information. 有关更多信息,请参阅结构包装
Multiple inheritance will produce implementation-specific memory layouts of possibly different sizes. 多重继承将产生可能不同大小的特定于实现的内存布局。 Virtual tables and virtual pointers for multiple virtual inheritance and type casting
用于多个虚拟继承和类型转换的虚拟表和虚拟指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.