在初始值设定项列表中使用空构造函数初始化父类

Initialize parent class with empty constructor in initializer list?

本文关键字:构造函数 父类 初始化 列表      更新时间:2023-10-16

不初始化子初始化列表中的空构造函数父类有危险吗?

示例:

class Parent
{
  public:
    Parent(){}
    ~Parent(){}
};
class Child : public Parent
{
  public:
    Child(): Parent()
    {}
    ~Child(){}
};

问题原因:我经常看到代码中带有空ctor的"Parent"类没有在子ctor初始化列表中初始化。

假设Parent没有用户提供的构造函数,例如,如果它是一个聚合:

struct Parent
{
    int x;
    int get_value() const { return x; }
};

现在有一个区别(参见[dcl.init]/(8.1)),因为Parent的值初始化将零初始化成员x,而默认初始化不会:

struct GoodChild : Parent { GoodChild() : Parent() {} };
struct BadChild : Parent { BadChild() {} };

因此:

int n = GoodChild().get_value(); // OK, n == 0
int m = BadChild().get_value();  // Undefined behaviour