我有一个更新外部引用的基类,我想构建一个继承类,将这个引用作为成员嵌入。引用的一种默认初始化。
我想出了以下解决方案:
#include<iostream>
class Statefull
{
public:
Statefull( int& ref ) : _base_ref(ref) {}
int& _base_ref;
// update the extern variable
void work() { std::cout << ++_base_ref << std::endl; }
};
class Stateless : public Statefull
{
public:
// use a temporary allocation
Stateless( int* p = new int() ) :
// we cannot initialize local members before base class:
// _dummy(), Statefull(_dummy)
// thus, initialize the base class on a ref to the temporary variable
Statefull(*p),
_tmp(p),
_dummy()
{
// redirect the ref toward the local member
this->_base_ref = _dummy;
}
int* _tmp;
int _dummy;
// do not forget to delete the temporary
~Stateless() { delete _tmp; }
};
int main()
{
int i = 0;
Statefull full(i);
full.work();
Stateless less;
less.work();
}
但是在构造函数的默认参数中需要临时分配似乎很丑陋。有没有更优雅的方法来实现这种默认初始化,同时在基类构造函数中保留引用?