我是靠谱客的博主 乐观奇异果,这篇文章主要介绍C++类与对象(3) - 空class&struct的大小1.空类大小2.为什么是13.空类的指针4.空基类的大小5.各情况下的类大小,现在分享给大家,希望可以做个参考。
目录
1.空类大小
2.为什么是1
3.空类的指针
4.空基类的大小
5.各情况下的类大小
C++中,不论是空类,还是空结构体,其大小都是为1。
1.空类大小
一个空类的大小通常为1。
#include<iostream>
class Empty {};
int main()
{
std::cout << "sizeof(Empty) = "<<sizeof(Empty);
return 0;
}
输出结果:
sizeof(Empty) = 1
2.为什么是1
空类大小为1,这样可以确保两个不同的对象,拥有不同的地址。
参考下面这个例子,可以看到两个对象的地址是不同的。
#include<iostream>
class Empty { };
int main()
{
Empty a, b;
if (&a == &b)
std::cout << "address equal, impossible!" << std::endl;
else
std::cout << "address not equal, excepted!" << std::endl;
return 0;
}
输出:
address not equal, excepted!
3.空类的指针
同样的原因 (不同对象拥有不同地址),new对象后,也会返回不同的指针。
如下面例子所示:
#include<iostream>
class Empty
{
};
int main()
{
Empty* p1 = new Empty;
Empty* p2 = new Empty;
if (p1 == p2)
std::cout << "address equal, impossible!" << std::endl;
else
std::cout << "address not equal, excepted!" << std::endl; return 0;
}
输出:
address not equal, excepted!
4.空基类的大小
参考下面程序,其中基类是一个空类。
#include<iostream>
class Empty { };
class Derived: Empty { int a; };
int main()
{
std::cout << "sizeof(Derived) = " << sizeof(Derived);
return 0;
}
输出:
sizeof(Derived) = 4
注意:输出值并没有预想中的那样会大于4,而是等于4!
这是一条很有趣的规则。即空的基类可以不依靠一个字节来表示。这样编译器碰到空的基类情况时,可以自由的进行优化。
5.各情况下的类大小
#include <iostream>
using namespace std;
class Empty {};
class Derived1 : public Empty {};
class Derived2 : virtual public Empty {};
class Derived3 : public Empty
{
char c;
};
class Derived4 : virtual public Empty
{
char c;
};
class Dummy
{
char c;
};
int main()
{
cout << "sizeof(Empty) " << sizeof(Empty) << endl;
cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;
cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;
return 0;
}
输出:
sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8 //这个case包括了内存对齐
sizeof(Dummy) 1
更多参考:
http://www2.research.att.com/~bs/bs_faq2.html
最后
以上就是乐观奇异果最近收集整理的关于C++类与对象(3) - 空class&struct的大小1.空类大小2.为什么是13.空类的指针4.空基类的大小5.各情况下的类大小的全部内容,更多相关C++类与对象(3)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复