为什么空类的大小是1个字节 [英] Why size of empty class is 1 byte

查看:248
本文介绍了为什么空类的大小是1个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么空类的大小是1个字节?

Why size of empty class is 1 byte?

推荐答案

你好亲爱的

i认为类的大小很大程度上取决于您用来编译类的操作系统或编译器。在此基础上,对于不同的操作系统或编译器,类的大小将不同

,因为在某些情况下,它将是1个字节(可能在64位环境中),有时它将显示为2或4个字节也取决于您尝试计算类大小的方式,就像使用sizeof运算符一样,sizeof()运算符可以返回至少 1字节数据而不是0字节。



hello dear
i think the size of the Class very much depends on the Operating system or the compiler you are using to compile the class. On that basis the size of the class will be different for different OS or the compilers
as in some cases it will be 1 byte (may be in 64 bit environment) and some times it will be shown as 2 or 4 bytes and also it depends on the way you are trying to calculate the size of the class as if you are using the sizeof operator then the sizeof() operator can return at least 1 byte data not 0 bytes.

Why is the size of an empty class not zero?

To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:
    class Empty { };

    void f()
    {
        Empty a, b;
        if (&a == &b) cout << "impossible: report error to compiler supplier";

        Empty* p1 = new Empty;
        Empty* p2 = new Empty;
        if (p1 == p2) cout << "impossible: report error to compiler supplier";
    }
There is an interesting rule that says that an empty base class need not be represented by a separate byte:
    struct X : Empty {
        int a;
        // ...
    };

    void f(X* p)
    {
        void* p1 = p;
        void* p2 = &p->a;
        if (p1 == p2) cout << "nice: good optimizer";
    }
This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".







以上代码的原始帖子'的网址: http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty [ ^ ]



我也在这里嵌入了不同网站的URL。这是 OK

如果我不想那样做,请告诉我。



上帝帮助程序员/开发人员。

最好的问候




Origional post''s URL for the above code : http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty[^]

also here i am embeding a URL of the different website. Is that OK
if i am not suppose to do that in that case let me know.

GOD Help Programmers/Developers.
Best regards


因为这是系统可以分配的最小内存量。
Because thats the minimum amount memory which can be allocated by system.


这篇关于为什么空类的大小是1个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆