what is the size of empty class in C++,java?

2019-01-25 05:58发布

What is the size of an empty class in C++ and Java? Why is it not zero? sizeof(); returns 1 in the case of C++.

8条回答
Rolldiameter
2楼-- · 2019-01-25 06:54

In the Java case:

  • There is no simple way to find out how much memory an object occupies in Java; i.e. there is no sizeof operator.
  • The size of an object (empty or non-empty) is platform specific.

The size of an instance of an "empty class" (i.e. java.lang.Object) is not zero because the instance has implicit state associated with it. For instance, state is needed:

  • so that the object can function as a primitive lock,
  • to represent its identity hashcode,
  • to indicate if the object has been finalized,
  • to refer to the object's runtime class,
  • to hold the object's GC mark bits,
  • and so on.

Current Hotspot JVMs use clever tricks to represent the state in an object header that occupies two 32 bit words. (This expands in some circumstances; e.g. when a primitive lock is actually used, or after identityHashCode() is called.)

查看更多
萌系小妹纸
3楼-- · 2019-01-25 06:54

Because every C++ object needs to have a separate address, it isn't possible to have a class with zero size (other than some special cases related to base classes). There is more information in C++: What is the size of an object of an empty class? .

查看更多
登录 后发表回答