struct constructor 将在 struct space 中使用 space?

struct constructor will take space within the struct space?

大多数时候我使用struct来保存我的套接字通信数据结构的所有参数,然后我可以轻松地复制、传递或将整个结构放在套接字上,只需传递起始地址及其尺寸。

如果我将构造函数添加到 struct 用于可变短数组,构造函数是否会占用结构中的任何 space?或者我可以将带有构造函数的 struct 与不带构造函数的 struct 相同,并将整个 struct 复制到套接字及其起始地址和大小,以及它的 space还在连续分配吗?

不,非虚拟成员函数不会对您的对象的 sizeof 做出贡献。至少存在一个虚函数(但构造函数不能是虚函数),因为编译器通常通过指向函数指针数组(vtable)的指针(vpointer)实现它们,因此它必须存储该指针(4或8通常为字节)。

这个问题与C++对象模型有关。正常功能不会增加数据大小。但是,如果我们添加虚函数,编译器会生成__vptr指向虚函数table,这会增加struct的数据大小。

比如我有a.C

#include <iostream>
using namespace std;
struct X
{
    X(){}
    int i;
    int j;

};

int main()
{
    X x;
    cout << sizeof(x) << endl;
}

在这里,我在我的机器上使用我的 IBM XL C++ 编译器进行编译,运行 它:

xlC -+ a.C
./a.out

输出将是 8,这与结构只有 int i 和 int j 相同。

但是如果我添加两个虚函数:

#include <iostream>
using namespace std;
struct X
{
    X(){}
    int i;
    int j;
    virtual void foo(){}
    virtual void bar(){}
};

int main()
{
    X x;
    cout << sizeof(x) << endl;
}

如果重新编译并运行它:

xlC -+ a.c
./a.out

输出将是 16。两个 int 为 8,__vptr 为 8(我的机器是 64 位)。