In C++, even an empty class (i.e., a class with no data members and member functions) does not have a size of 0 bytes when an object is created. This is because each instance requires a unique address to distinguish them from each other. According to the C++ standard, an empty class object must occupy at least 1 byte.
For example, define an empty class:
cppclass EmptyClass {};
Then, we can test the size of the object:
cpp#include <iostream> class EmptyClass {}; int main() { EmptyClass obj; std::cout << "Size of object is: " << sizeof(obj) << " byte." << std::endl; return 0; }
The output of this code will be:
shellSize of object is: 1 byte.
This indicates that even if the class has no data members or member functions, each object still occupies 1 byte of space, primarily to ensure that each object has a unique address in memory.
2024年6月29日 12:07 回复