2

我收到了以下与以下相关的问题sizeof()

class C
{
public:
    C();
    virtual ~C();

    unsigned char _member0 s[4];
    static long _member1 d;
}

int main()
{
    C vc;
    cout << sizeof(vc);
}

有人可以解释sizeof()在这种情况下如何评估函数吗?

4

2 回答 2

7

The exact answer could vary from compiler to compiler so in strict sense the answer to your question is this is Implementation Defined.
Considering this to be an interview Q(saw your previous Q), You should have pointed out the following points:

  • A compiler is allowed to add padding bytes to a structure/class,this might add to the size.
  • A compiler might add vptr to an class instance,this might add to the size.
  • The class members will occupy memory.
  • static members do not contribute towards the size of an class object because they do not belong to an instance of class but to the class.
于 2012-08-30T07:07:28.737 回答
0

它给出了vc的大小。vc 属于 C 类。C 类的每个对象都包含元数据(指向 vtable 的指针),因为 C 包含虚方法。此外,C 有一个数据字段(字符数组)。

因此 vc 的大小应该是指针的大小加上四个字节(加上填充,请参阅下面的评论,谢谢)。

d 不是 C 类对象的组成部分,因为它是静态的,因此不计算在内。

所以我们有:

------vc---------             ----vtable for C----           ----statics----
| ptr to vtable | ----------> | pointer to ~C    |           | C::d        |       
|---------------|             | ...              |           | ...         |
| char [4]      |             --------------------           ---------------
-----------------
于 2012-08-30T07:04:34.840 回答