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

前端 未结 8 2113
北恋
北恋 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: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)

提交回复
热议问题