C++: What is the size of an object of an empty class?

后端 未结 16 1778
悲&欢浪女
悲&欢浪女 2020-11-22 11:54

I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 12:29

    This may help u :-) http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a

    The sizeof an empty class or structure is 1

    The reason this happens boils down to properly implementing the standard, one of the things the C++ standard says is that "no object shall have the same address in memory as any other variable".... What is the easiest way to ensure this? Make sure that all types have a non-zero size. In order to achieve this the compiler adds a dummy byte to structures and classes that have no data members and no virtual functions so that they have a size of 1 rather than a size of 0 and then they are guaranteed to have a unique memory address.

提交回复
热议问题