学习 C++ / 第 13.11 课

结构体杂项

9 分钟阅读

包含程序定义成员的结构体

在 C++ 中,结构体(以及类)可以拥有其他用户定义类型的成员。实现方式有两种。

第一种方式是先定义一个用户类型(位于全局作用域),再把它用作另一个用户类型的成员:

C++
#include <iostream>

struct Employee
{
    int id {};
    int age {};
    double wage {};
};

struct Company
{
    int numberOfEmployees {};
    Employee CEO {}; // Employee 是 Company 结构体中的结构体
};

int main()
{
    Company myCompany{ 7, { 1, 32, 55000.0 } }; // 使用嵌套初始化列表初始化 Employee
    std::cout << myCompany.CEO.wage << '\n'; // print the CEO's wage

    return 0;
}

在上面的例子中,我们定义了一个 Employee 结构体,然后将它用作另一个 Company 结构体的成员。初始化 Company时,也可以使用嵌套初始化列表初始化 Employee 。如果想知道 CEO 的工资,只需连续使用两次成员选择运算符: myCompany.CEO.wage;

第二种方式是把类型嵌套在其他类型中。如果 Employee 只作为 Company 的一部分存在,就可以把 Employee 类型嵌套在 Company 结构体中:

C++
#include <iostream>

struct Company
{
    struct Employee // 通过 Company::Employee 访问
    {
        int id{};
        int age{};
        double wage{};
    };

    int numberOfEmployees{};
    Employee CEO{}; // Employee 是 Company 结构体中的结构体
};

int main()
{
    Company myCompany{ 7, { 1, 32, 55000.0 } }; // 使用嵌套初始化列表初始化 Employee
    std::cout << myCompany.CEO.wage << '\n'; // print the CEO's wage

    return 0;
}

这种做法更常见于类,我们会在后续课程中详细讨论(15.3 -- 嵌套类型(成员类型)).

作为所有者的结构体,其数据成员也应是所有者

在课程 5.9 -- std::string_view (part 2)中,我们介绍了“所有者”和“观察者”这两个概念。所有者管理自己的数据,并控制数据何时销毁;观察者查看他人的数据,但不控制数据何时修改或销毁。

大多数情况下,我们希望结构体(以及类)成为其所含数据的所有者。这会带来一些好处:

  • 只要结构体(或类)存在,其数据成员就始终有效。
  • 这些数据成员的值不会意外改变。

让结构体(或类)成为所有者的最简单方法,是让每个数据成员都使用所有者类型(例如,不使用观察者、指针或引用)。如果结构体或类的所有数据成员都是所有者,那么它本身也会自动成为所有者。

如果结构体(或类)包含观察者数据成员,那么被观察的对象可能在该成员之前销毁。这样一来,结构体会留下悬空成员,访问该成员将导致未定义行为。

最佳实践

大多数情况下,我们希望结构体(以及类)是所有者。最简单的做法是确保每个数据成员都使用所有者类型(例如,不使用观察者、指针或引用)。

作者注

请编写安全的结构体,不要让成员悬空。

这就是字符串数据成员几乎总是使用 std::string (它是所有者类型),而不是 std::string_view (它是观察者类型)的原因。下面的例子展示了这一点:

C++
#include <iostream>
#include <string>
#include <string_view>

struct Owner
{
    std::string name{}; // std::string 是所有者
};

struct Viewer
{
    std::string_view name {}; // std::string_view 是查看者
};

// getName() 将用户输入的字符串作为临时 std::string 返回
// 这个临时 std::string 会在完整表达式结束时销毁
// containing the 函数调用。
std::string getName()
{
    std::cout << "Enter a name: ";
    std::string name{};
    std::cin >> name;
    return name;
}

int main()
{
    Owner o { getName() };  // getName() 的返回值在初始化后立即销毁
    std::cout << "The owners name is " << o.name << '\n';  // 正确

    Viewer v { getName() }; // getName() 的返回值在初始化后立即销毁
    std::cout << "The viewers name is " << v.name << '\n'; // undefined behavior

    return 0;
}

getName() 函数会将用户输入的姓名作为临时对象返回 std::string。这个临时返回值会在调用该函数的完整表达式结束时销毁。

对于 o,这个临时对象 std::string 被用来初始化 o.name。由于 o.name 是 std::string,它会复制临时对象 std::string。临时对象 std::string 随后销毁,但 o.name 不会受到影响,因为这里保存的是副本。随后输出 o.name 时,程序会按预期工作。

对于 v,这个临时对象 std::string 被用来初始化 v.name。由于 v.name 是 std::string_view,v.name 只是临时 std::string 的视图,而不是副本。临时对象 std::string 随后销毁,使 v.name 悬空。随后输出 v.name 时,就会产生未定义行为。

结构体大小与数据结构对齐

通常,结构体的大小等于所有成员大小之和,但并非总是如此!

请看下面的程序:

C++
#include <iostream>

struct Foo
{
    short a {};
    int b {};
    double c {};
};

int main()
{
    std::cout << "The size of short is " << sizeof(short) << " bytes\n";
    std::cout << "The size of int is " << sizeof(int) << " bytes\n";
    std::cout << "The size of double is " << sizeof(double) << " bytes\n";

    std::cout << "The size of Foo is " << sizeof(Foo) << " bytes\n";

    return 0;
}

在作者的机器上,输出结果是:

C++
The size of short is 2 bytes
The size of int is 4 bytes
The size of double is 8 bytes
The size of Foo is 16 bytes

请注意,short + int + double 的大小为 14 字节,而 Foo 大小为 16 字节!

事实证明,我们只能说结构体的大小 至少 与其中所有变量的大小相同,但它也可能更大!出于性能原因,编译器有时会在结构体中加入间隙(这称为 填充).

在上面的 Foo 结构体中,编译器在成员 a 后加入了填充,使结构体大小从 14 字节变成 16 字节。

进阶读者

编译器添加填充的原因超出了本教程范围;想深入了解的读者可以阅读 数据结构对齐 (维基百科)。这是扩展阅读,不是理解结构体或 C++ 所必需的内容!

这实际上会显著影响结构体大小,下面的程序说明了这一点:

C++
#include <iostream>

struct Foo1
{
    short a{}; // will have 2 bytes of 填充 after a
    int b{};
    short c{}; // will have 2 bytes of 填充 after c
};

struct Foo2
{
    int b{};
    short a{};
    short c{};
};

int main()
{
    std::cout << sizeof(Foo1) << '\n'; // prints 12
    std::cout << sizeof(Foo2) << '\n'; // prints 8

    return 0;
}

程序输出:

12
8

请注意, Foo1 and Foo2 拥有相同的成员,唯一差别是声明顺序。然而 Foo1 由于增加了填充,大小却大了 50%。

提示

按成员大小递减的顺序定义成员,可以减少填充。

C++ 编译器不允许重新排列成员,因此必须手动完成。

最后更新