C++类与对象(3) - 空class&struct的大小

目录

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值