gpt4 book ai didi

c++ - 使用派生类成员进行父类的初始化

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:50 24 4
gpt4 key购买 nike

我想初始化一个派生自类 A 的类 B,在 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。此外,GCC 提示说

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

有没有更合适的解决方案?

最佳答案

你按原样做的是未定义的行为,来自 [class.base.init]/14,强调我的:

Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined.

您要做的是使用 Base-from-Member idiom :

class Cache {
protected:
const SomeDataType cache_;
};

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

关于c++ - 使用派生类成员进行父类的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30438446/

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