在初始值设定项列表中使用空构造函数初始化父类
Initialize parent class with empty constructor in initializer list?
不初始化子初始化列表中的空构造函数父类有危险吗?
示例:
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
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 参数包构造函数在类模板中隐藏用户定义的转换
- 具有已删除移动和复制构造函数的类的就地构造
- 创建一个没有复制构造函数的类的 std::vector 的 std::vector
- C++构造函数和类?
- 在 C++ 中,默认情况下构造函数为类的数据成员提供的值是多少?
- 如何在其他类中使用参数化构造函数制作类的对象?
- 具有值包装器的可变参数模板构造函数的类构造函数优先级
- 如何使用私有构造函数对类进行单元测试?
- c++17在编译时将带有已删除复制构造函数的类添加到std::vector
- 从作为模板参数传递给构造函数的类继承,或者从它们继承
- 继承的构造函数忽略类内初始化
- 模板和隐式构造函数的类定义之外的友元声明
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- C++ - 从另一个类构造函数调用类构造函数
- 定义结构中没有默认构造函数的类
- 我可以将 std::move 与不提供 move 构造函数的类一起使用吗?
- 是否可以默认初始化具有已删除默认构造函数的类类型
- C++具有移动和复制构造函数的类中的代码重复
- 在C++中,如何测试对象是否是父类构造函数中子类的实例?