简体   繁体   English

C ++-应用于对象类的sizeof函数

[英]C++ - sizeof function applied to object class

I received the following question which was related to sizeof() : 我收到以下与sizeof()有关的问题:

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

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

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

Can someone explain how the sizeof() function is evaluated in this case? 有人可以解释在这种情况下如何评估sizeof()函数吗?

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: 认为这是一次采访Q( 看过您以前的Q ),您应该指出以下几点:

  • 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. 编译器可能将vptr添加到类实例中,这可能会增加大小。
  • 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. static成员不会增加类对象的大小,因为它们不属于类的实例,而是属于该类。

It gives the size of vc. 它给出了vc的大小。 vc is of class C. Each object of class C contains metadata (pointer to vtable), since C contains virtual methods. vc是C类。C类的每个对象都包含元数据(指向vtable的指针),因为C包含虚方法。 In addition, C has a data field (the character array). 另外,C有一个数据字段(字符数组)。

Hence the size of vc should be the size of a pointer plus four bytes (plus padding, see comment below, thanks). 因此,vc的大小应为指针的大小加上四个字节(加上填充,请参见下面的注释,谢谢)。

d is not component of an object of class C, since it is static, hence it does not count. d不是C类对象的组成部分,因为它是静态的,因此不算在内。

So we have: 所以我们有:

------vc---------             ----vtable for C----           ----statics----
| ptr to vtable | ----------> | pointer to ~C    |           | C::d        |       
|---------------|             | ...              |           | ...         |
| char [4]      |             --------------------           ---------------
-----------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM