使用派生类成员初始化父类
Using derived class members for the initialization of the parent class
我想初始化一个从类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]。/14,强调mine:
可以为正在构造的对象调用成员函数(包括虚成员函数,10.3)。类似地,正在构造的对象可以是
typeid
操作符(5.2.8)或dynamic_cast
操作符(5.2.7)的操作数。但是,如果在变量初始化器中执行这些操作(或在直接调用的函数中),则在基类的所有mem-初始化器s完成之前,或间接地从元素初始化器)中获取结果.
你要做的是使用Base-from-Member的习惯用法:
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_;
};
相关文章:
- C++初始化基类
- 为什么在C++中首先初始化成员类
- 初始化指向类实例的智能指针并访问其方法
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 初始化模板类中的固定长度数组
- 从模板化父类中的派生内部类访问受保护的成员变量
- 使用 Clang LibTooling 扫描C++在模板化父类中调用本地类的源
- 在 C++11 中轻松初始化模板类的静态成员,没有 clang 警告
- 如何从子类的构造函数初始化父类的私有成员
- C++构造函数如何初始化其类的对象?
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 如何从静态类函数初始化静态类对象
- 如何初始化对类内变量的静态引用,以便在嵌套类中使用
- c++:可以使用父构造函数初始化子类中的数据吗?
- 在初始值设定项列表中使用空构造函数初始化父类
- 使用派生类中的成员初始化父类中的std::函数
- 不显式初始化父类的虚拟继承
- 错误:基类构造函数必须显式初始化父类构造函数
- 在子类中初始化父类的 const 成员
- 使用派生类成员初始化父类