Sizeof empty class

前端 未结 3 826
情歌与酒
情歌与酒 2021-01-12 11:31

With the code:

#include 

class A {};
class B { char x; };

int main()
{
    std::cerr << sizeof(A) << \" \" << sizeof(B) &         


        
3条回答
  •  时光取名叫无心
    2021-01-12 12:02

    This isn’t really a meaningful question: The runtime just marks the one byte as occupied so that no other object will be allocated at its position. But there isn’t anything “held” there to occupy the byte.

    The only reason for this rule is that objects must be uniquely identifiable. An object is identified by the address it has in memory. To ensure that no two objects have the same address (except in the case of base class objects), objects of empty classes “occupy” memory by having a non-zero size.

提交回复
热议问题