簡體   English   中英

使用派生類成員進行父類的初始化

[英]Using derived class members for the initialization of the parent class

我想初始化類B這是一個從類派生A ,並且其中在B我構造的高速緩存首先進行使用的建設A ,例如

class B: public A {

public:
  B(): A(cache_), cache_(this->buildCache_())

protected:
  const SomeDataType cache_;

private:
  SomeDataType
  buildCache_() const
  {
    // expensive cache construction
  }

}

不會工作,雖然因父對象A總是先初始化(前cache_充滿)。

(出於完整性考慮: cache_在從B派生的類中被多次使用。)

作為替代,我可以做

class B: public A {

public:
  B(): A(this->buildCache_())

protected:
  const SomeDataType cache_;

private:
  SomeDataType
  buildCache_()
  {
    // expensive cache construction
    // fill this->cache_ explicitly
    return cache_;
  }

}

這樣做的缺點是buildCache_()不能為const 另外,海灣合作委員會抱怨說

warning: ‘B::cache_’ should be initialized in the member initialization list [-Weffc++]

有沒有更合適的解決方案?

您所做的是[class.base.init] / 14中未定義的行為,重點是我的:

可以為正在構造的對象調用成員函數(包括虛擬成員函數10.3)。 同樣,正在構造的對象可以是typeid運算符(5.2.8)或dynamic_cast (5.2.7)的操作數。 但是,如果在所有基類的mem-initializer完成之前,在ctor初始化程序 (或直接或間接從ctor初始化程序調用的函數)中執行了這些操作,則操作的結果是不確定的

您想要做的是使用“ 從成員開始”成語

class Cache {
protected:
    const SomeDataType cache_;
};

class B : private Cache, public A {
public:
    B() : Cache(), A(cache_)
    { }
};

從C ++ 11,您可以使用正向構造函數:

class B: public A
{
public:
  B(): B(B::buildCache_()) {}

private:
  B(SomeDataType&& cache) : A(cache), cache_(std::move(cache)) {}

private:
  static SomeDataType buildCache_()
  {
    // expensive cache construction
  }

protected:
    const SomeDataType cache_;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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