Why is the size of an empty class not 0?
This is necessary to ensure that two different objects have different addresses.
The instantiation of a class is the allocation of an address in memory, with each instance having a unique two address in memory.
Similarly, an empty class is instantiated, so the compiler adds a byte implicitly to the empty class so that the empty class is instantiated with a unique address.
Therefore, the empty class of sizeof is 1, not 0.
An empty class is no longer empty after the C + + compiler is processed, and the compiler automatically declares some member function for us,
If you write
Class a{};
After the compiler is processed, it is equivalent to:
Class a{Public: A (); Default constructor A (const a&); Copy constructor ~a (); destructor a& operator= (const a& RHS); A * operator& (); Fetch address operator
Now make the following statement:
After reading the above example, you may feel that declaring an empty class, we all think will generate constructors, copy constructors, destructors, assignment operation symbols, accessor operator const, access operator.
in fact, ah, then an empty class when is not empty class it? in fact, for such an empty class, it is completely unnecessary, and the compiler does not do so. The compiler does this: only if you need to use these functions and you do not show the declaration of these functions, the compiler will be intimate to automatically declare the corresponding function.
class a{};
For an empty class A that is declared individually, there is no discovery in the compiler compilation process to create an instance of a.
So for an empty Class A, the compiler does not generate any functions for Class A.
If we need to generate an instance of a in the code
Like what
A;
The compiler generates constructors and destructors for Class A based on the example above.
When using
A B (b);
The compiler generates a copy constructor for Class A.
A C;
c = A;
Compiler-generated assignment operator functions
a &d = A;
The compiler generates the fetch address operator function.
This is understood by our analysis: For an empty class that is not instantiated, the compiler does not generate any functions for it, and when an empty class is instantiated, the compiler generates the corresponding function as needed. This theory is also suitable for non-empty classes (declaring variables only, not declaring functions).
What default functions are generated when an empty class is compiled by the compiler