[英]Why can't I initialize an ifstream in the initializer list of the constructor of a class?
[英]Initialize parent class with empty constructor in initializer list?
在子初始化列表中不初始化空的構造函數父類是否有危險?
例:
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
零初始化,而default-initialization則不會:
struct GoodChild : Parent { GoodChild() : Parent() {} };
struct BadChild : Parent { BadChild() {} };
因此:
int n = GoodChild().get_value(); // OK, n == 0
int m = BadChild().get_value(); // Undefined behaviour
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.