Question: What is sizeof for an empty class?
Let's take a look at the test code. The result is printed on the G ++ 4.5 64bit machine.
#include <iostream>using namespace std;class ClassA {};class ClassB { private: int b;};class ClassC : public ClassA {};class ClassD : public ClassB {};class ClassE { public: int GetReturnValue() { return 0; }};struct StructA {};int main() { cout << "ClassA " << sizeof(ClassA) << endl; cout << "ClassB " << sizeof(ClassB) << endl; cout << "ClassC " << sizeof(ClassC) << endl; cout << "ClassD " << sizeof(ClassD) << endl; cout << "ClassE " << sizeof(ClassE) << endl; cout << "StructA " << sizeof(StructA) << endl;}
The result is as follows:
ClassA 1ClassB 4ClassC 1ClassD 4ClassE 1StructA 1
When a class can be instantiated, the compiler needs to allocate memory space to it to indicate the address of the class instance. Here, the compiler allocates a byte (for example, Char, compiler-related) by default to mark classes that may be initialized, and at the same time, the space occupied by the empty class is also minimal (that is, 1 byte ).
The size of struct and empty classes is 1. First, this is a C ++ problem. In C, the size of empty struct is 0 (of course, this is related to the compiler ). Here, the empty class and empty struct mean that there is no Member in the class or struct.
In C ++, the size of the null class and the empty struct is 1 (compiler-related). Why? Why is it not 0?
This is because the C ++ standard stipulates that "No
Object shall have the same address in memory as any other variable "means that different objects cannot have the same memory address. If the empty class is 0, If we declare an array of objects of this class, each object in the array has the same address, which is obviously against the standard.
[Reference]
Http://www.spongeliu.com/%E8%AF%AD%E8%A8%80%E5%AD%A6%E4%B9%A0/clanguage/why-not-null/
Http://blog.csdn.net/sunboy_2050/article/details/6589999