C++中内存分配问题,
在结构体和类中,有很多问题都是求sizeof问题,这个问题不是简单的算出各个类型的长度然后相加就行了,而是要考虑编译器是如何编译这些代码的,是如何为结构体和类中的变量怎么分配内存空间的。http://blog.csdn.net/jimmy54/article/details/5418766,这个地址中讲述了类中的存储情况。下面是我在QT中的代码测试:
#include <QCoreApplication>
#include <iostream>
using namespace std;
class A{
A();
~A();
void function();
};
//#pragma pack(1)
class B{
private:
char a;
int b;
//double d;
char c[2];
};
//#pragma pack()
class I{
public:
virtual void func();
};
//#pragma pack(1)
class C:public B{
public:
//struct B;
virtual void func();
char d[9];
// char d[12];
double a;
char b[5];
};//sizeof(C)=4(虚函数地址)+sizeof(B)+d[9]自然对齐+8(double类型)+b[5]最后类成员补齐
//即:4+12+9(12)+8+5(12)=48
//#pragma pack()
class D{
public:
static int count;
int a;
double b;
char c;
};
class E{
public:
static int count;
double b;
int a;
char c;
};
class F{
public:
static int count;
char c;
double b;
int a;
};
class H{
public:
char c;
int a;
double b;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<<" long is "<<sizeof(long)<<endl;
cout<<" int is "<<sizeof(int)<<endl;
cout<<" long long is "<<sizeof(long long)<<endl;
cout<<" double is "<<sizeof(double)<<endl;
cout<<" sizof(A) is "<<sizeof(A)<<endl;
cout<<" sizof(B) is "<<sizeof(B)<<endl;
cout<<" sizof(I) is "<<sizeof(I)<<endl;
cout<<" sizof(C) is "<<sizeof(C)<<endl;
cout<<" sizof(D) is "<<sizeof(D)<<endl;
cout<<" sizof(E) is "<<sizeof(E)<<endl;
cout<<" sizof(F) is "<<sizeof(F)<<endl;
cout<<" sizof(H) is "<<sizeof(H)<<endl;
return a.exec();
}
结果:
long is 4
int is 4
long long is 8
double is 8
sizeof(A) is 1
sizeof(B)is 12
sizeof (I)is 4
sizeof (C)is 48
sizeof(D)is 24
sizeof (E)is 16
sizeof (F)is 24
sizeof (H)is 16