我的类包含 1 个枚举、2 个 int 和一个指针。它没有虚函数,但测量 20 字节。为什么?

My class contains 1 enum, 2 int's and a pointer. It has no virtual functions but measures 20 bytes. Why?

本文关键字:函数 测量 为什么 字节 一个 枚举 包含 int 我的 指针      更新时间:2023-10-16

根据标题。我真的不想列出它包含的所有其他成员,但我惊讶地发现,给定唯一的非静态数据成员是intenum、2和指向它自己类型的指针,它的sizeof应该是20。

它没有虚拟函数,我已经将指针和enum分别测量为4个字节。我应该更努力地寻找其他成员吗?

当从文件中读回时,我需要这些信息来为其类型的n个对象分配缓冲区。

平台:bada,环境:gcc和Eclipse在Win7 x64中。

enum blockParams {enum1, enum2, /**/};
class Block : public Object {
public:
    int begin;
protected:
    Block() : begin(-1), end(UNCLOSEDBLOCK) {}
    //Last index
    int end;
private:
    blockParams1 params;
    const Block *parentBlock;
//Lots and lots (~80) member functions and static data members.
}

编译器可以自由地在成员之间引入填充,以实现各种对齐要求。

许多编译器提供了一种不可移植的方式来更紧密地封装结构(例如GCC的__attribute ((packed))),但很少有充分的理由使用这种方式。

当我看到一个名为Object的基类型时,我真的怀疑没有虚拟函数的说法。

如果正确使用sizeof,则不需要知道结构的大小,编译器将为您正确计算缓冲区大小。

20的大小可能包括编译器为提高效率而添加的填充。

大小是部分+填充的总和。

int main()
{
    std::cout << "Object:       " << sizeof(Object) << "n";
    std::cout << "int:          " << sizeof(int) << "n";
    std::cout << "blockParams1: " << sizeof(blockParams1) << "n";
    std::cout << "Block*:       " << sizeof(Block*) << "n";
    int estimatedSize = sizeof(Object) + (2 * sizeof(int)) + sizeof(blockParams1) + sizeof(Block*);
    int actualSize    = sizeof(Block);
    std::cout << "Block:        " << actualSize << "n";
    std::cout << "Padding + implementation defined data for virtual functions:      " <<  (actualSize - estimatedSize) << "n";
}

在对象为空的情况下运行此操作:

> ./a.out
Object:       1 // Note: This may be optimized away in Block.
                //       All objects must have non 0 size but when they are a base class
                //       you can optimize an actual zero sized object away.
int:          4
blockParams:  4
Block*:       8
Block:        24
Padding + implementation defined data for virtual functions:      3
// Note because the Object size 1 will be optimized away this is actually 4.

使用包含虚拟析构函数的对象运行此

> ./a.out
Object:       8
int:          4
blockParams:  4
Block*:       8
Block:        32
Padding + implementation defined data for virtual functions:      4
// Note It will use the area in Object for virtual functions so it does not
//      Explicitly need any itself (in this implementation using a vtable).

如果我们假设您的平台上的指针是4个字节(并且您有带有虚拟函数的Object)。我希望看到:

> ./a.out
Object:       4
int:          4
blockParams:  4
Block*:       4
Block:        20
Padding + implementation defined data for virtual functions:      0