Today's interview is an interesting question: what is the amount of memory that an empty struct occupies in C + +? See the following code:
#include <iostream>struct s0{}; int Main () { sizeof S0 << std::endl; return 0 ;}
The interviewer alerted me on the spot, saying that if the S0 object occupies a memory size of 0, it will be able to request an infinite number of objects of this type, and the size will always be 0. I thought it was a bit of a reason, but then I thought it was a little bit confusing.
Back to study, originally in the C + + language does stipulate that empty structure and empty class accounted for the memory size of 1, while the C language hollow class and empty structure occupies a size of 0(test in GCC is 0, other compilers do not necessarily). This raises a new question: why does C + + have such a rule?
Originally, the C + + language standard stipulated a principle: "no object shall has the same address in memoryas any other variable", that is, any different objects cannot have the same memory address. If the empty class object size is 0, then the address of each object in such an array will be consistent, which is a clear violation of this principle.
Further, why does the C + + make such a provision? Take a look at the following example of the number of calculated elements:
T array[5]; int count = &array[4]-&array[0];
The operation of this pointer subtraction is equivalent to the following steps in the compiler:
Count = ((char *) &array[4]-(char *) &array[0sizeof T;
If the C + + object size is allowed to be 0, then the operation here will produce two questions:(1) the different array objects cannot be distinguished by pointers ;(2) sizeof T causes illegal except 0 operations for 0 . In this way, the compiler also needs to use some complex code to handle these exception condition information.
The C + + compiler guarantees that the size of any type object cannot be 0 for different objects that meet the requirements of the C + + standard cannot have the same address. the C + + compiler adds a dummy byte to an empty class or an empty struct (some compilers may have more than one) to ensure that different objects have different addresses.
Empty class and empty struct size in C + +