e******d 发帖数: 310 | 1 Given class A and class B, class A is an empty class and class B has one data member whose type is char; their definitions are as follows:
============================
class A
{
};
class B
{
private:
char c;
};
int n1 = sizeof(A); //n1 = 1;
int n2 = sizeof(B); //n2 = 1;
================================
The question is why n1 is equal to 1.
Thank you a lot. |
z****e 发帖数: 2024 | 2 an naive answer is:
for every empty class, it has to have a dummy byte to hold the unique
address for an object to be instantiated. |
e******d 发帖数: 310 | 3 Thank you for your input.
But I am not quite clear about your statement. My understanding is like this: if an address should be kept, then the size should be 4 bytes instead of 1 given the code is compiled in 32-bit mode. |
z****e 发帖数: 2024 | 4 think again,
1. what's the size of a char?
2. can you take address of a char?
this: if an address should be kept, then the size should be 4 bytes instead
of 1 given the code is compiled in 32-bit mode.
【在 e******d 的大作中提到】 : Thank you for your input. : But I am not quite clear about your statement. My understanding is like this: if an address should be kept, then the size should be 4 bytes instead of 1 given the code is compiled in 32-bit mode.
|
z****e 发帖数: 2024 | 5 actually, i think my previous answer is a little bit misleading.
the byte is not going to "hold" the address, but to make it possible that
the instantiation can have an unique address. the smallest cost is 1 byte of
memory to do so.
clear?
this: if an address should be kept, then the size should be 4 bytes instead
of 1 given the code is compiled in 32-bit mode.
【在 e******d 的大作中提到】 : Thank you for your input. : But I am not quite clear about your statement. My understanding is like this: if an address should be kept, then the size should be 4 bytes instead of 1 given the code is compiled in 32-bit mode.
|