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

前端 未结 8 2068
北恋
北恋 2020-12-03 17:35

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条回答
  • 2020-12-03 18:08

    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.
    • There are a few ways (e.g. using Instrumentation or 3rd party libraries) that will give you a number, but the meaning is nuanced1; see In Java, what is the best way to determine the size of an object?
    • 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.)


    1 - For example, does the size of the string object created by new String("hello") include the size of that backing array that holds the characters? From the JVM perspective, that array is a separate object!

    0 讨论(0)
  • 2020-12-03 18:13

    As others have pointed out, C++ objects cannot have zero size. Classes can have zero size only when they act as a subclass of a different class. Take a look at @Martin York's answer for a description with examples --and also look and vote the other answers that are correct to this respect.

    In Java, in the hotspot VM, there is a memory overhead of 2 machine-words (usually 4 bytes in a 32 arch per word) per object to hold book keeping information together with runtime type information. For arrays a third word is required to hold the size. Other implementations can take a different amount of memory (the classic Java VM, according to the same reference took 3 words per object)

    0 讨论(0)
提交回复
热议问题