簡體   English   中英

在初始化列表中使用空構造函數初始化父類?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM