在初始化列表中使用空构造函数初始化父类?

时间:2014-09-05 21:13:53

标签: c++

在子初始化列表中初始化空构造函数父类是否有任何危险?

示例:

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

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

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

1 个答案:

答案 0 :(得分:1)

假设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