看到阿里的一道筆試題:
#pragma pack(2)
class A
{
int i;
union U
{
char buff[13];
int i;
}u;
void foo() { }
typedef char* (*f)(void*);
enum{red, green, blue} color;
}a;
答案應該是多少呢:22
因爲對於u是14個字節,因爲u要設定爲每一個類型的整數倍,且能容納類型變量字節的最大值,但是這裏有這樣一個宏
#pragma pack(2),這個編譯器提供的宏能使變量一n字節的方式對齊,謝謝pxhero2012的指正
既然這樣,我們順便來總結一下c++中類的內存大小:
這是一個總結:
#include <iostream>
#include <iomanip>
using namespace std;
class A1//c++要求每個實例在內存中都有獨一無二的地址,空類也會被實力化,編譯器自動添加一個字節
{};
class A2
{
int a;
char p;
};
class A21//所有類型都小於處理器的大小,優化爲最大類型的整數倍
{
int a;
char b;
char c[6];
};
class A22//單個字符存儲,不會優化
{
char b;
char c[5];
};
class A23//double大於處理器位數,以處理器位數對齊
{
int a;
double b;
char c[2];
char d[7];
};
class B//含有虛函數的類中自動維護一個指向虛函數表的指針,大小爲4字節
{
public:
B(){}
virtual ~B(){}
private:
int a;
char *b;
};
class C: public B
{
public:
C(){}
~C(){}
virtual void func();//父類和子類共享一個 vptr,而不管虛函數的個數
private:
int x;
};
int main()
{
cout<<"A1:"<<setw(4)<<sizeof(A1)<<endl;
cout<<"A2:"<<setw(4)<<sizeof(A2)<<endl;
cout<<"A21:"<<setw(4)<<sizeof(A21)<<endl;
cout<<"A22:"<<setw(4)<<sizeof(A22)<<endl;
cout<<"A23:"<<setw(4)<<sizeof(A23)<<endl;
cout<<"B:"<<setw(4)<<sizeof(B)<<endl;
cout<<"C:"<<setw(4)<<sizeof(C)<<endl;
return 0;
}
對於c++關於繼承層次的內存佈局,準備去看《inside the c++ object module》
今天又看到了這樣的題目:再補上一道題
struct P1
{
int i;
char c;
int j;
char d;
};
struct P2
{
int i;
char c;
char d;
int j;
};
struct P3
{
short w[3];
char c[3];
};
struct P4
{
short w[2];
char *c[3];
struct P1
{
int i;
char c;
int j;
char d;
};
struct P2
{
int i;
char c;
char d;
int j;
};
struct P3
{
short w[3];
char c[3];
};
struct P4
{
short w[2];
char *c[3];
struct P1
{
int i;
char c;
int j;
char d;
};
struct P2
{
int i;
char c;
char d;
int j;
};
struct P3
{
short w[3];
char c[3];
};
struct P4
{
short w[3];
char *c[3]; };
struct P5
{
struct P1 a[2];
struct P2 *p;
};
printf("%d\n",sizeof(P1));//16
printf("%d\n",sizeof(P2));//12
printf("%d\n",sizeof(P3));//10
printf("%d\n",sizeof(P4));//20
printf("%d\n",sizeof(P5));//36
前幾個都沒有問題,第四個,這裏c的大小的是4字節,所以以4個字節對齊