gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:42:35 27 4
gpt4 key购买 nike

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

例子:

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

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

问题原因:我经常看到代码中没有在子 ctor 初始化列表中初始化具有空 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

关于c++ - 在初始化列表中使用空构造函数初始化父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694061/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com