【问题标题】:C++ default initialization in constructor of an inherited reference member继承的引用成员的构造函数中的 C++ 默认初始化
【发布时间】:2012-07-18 08:33:30
【问题描述】:

我有一个更新外部引用的基类,我想构建一个继承类,将这个引用作为成员嵌入。引用的一种默认初始化。

我想出了以下解决方案:

#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();
}

但是在构造函数的默认参数中需要临时分配似乎很丑陋。有没有更优雅的方法来实现这种默认初始化,同时在基类构造函数中保留引用

【问题讨论】:

  • 您没有重定向引用。您刚刚为 _base_ref 引用的变量分配了一个来自 dummy 的值。您不能重定向引用,只能初始化它们。
  • 继承层次有意义吗?我希望Stateless 成为基类,或者第三类作为公共基类。
  • @SimonRichter 问题是_ref_base 的声明,在Stateless 中它不应该是引用,在Statefull 中,它是。如果我不想重新实现work,则需要在基类中将_ref_base 声明为模板,我希望避免这样做。

标签: c++ inheritance reference constructor initialization


【解决方案1】:

好吧,Stateless 类违反了三法则。但我认为这是因为这只是展示真正问题的示例代码。

现在,要实际解决这个问题:将引用绑定到未初始化的变量是完全有效的,只要在初始化实际发生之前未使用它的值。

Stateless() : Statefull(_dummy), _dummy() {}

目前的解决方案有效,但似乎对为什么有效。

    // redirect the ref toward the local member
    this->_base_ref = _dummy;

您不能“重定向”引用。您只能绑定一次引用:在初始化时。分配给引用会分配给它所引用的对象。在这种情况下,this-&gt;_base_ref = _dummy *_tmp = _dummy 完全相同:它将_dummy 的值分配给*_tmp。但是,_base_ref 仍然指的是*_tmp(您可以使用assert(&amp;_base_ref == tmp) 对此进行测试)。

【讨论】:

  • “只要在初始化实际发生之前它的值没有被使用”确实。在我的真实示例中,这会很烦人……
【解决方案2】:

我认为这可能有效:

StateLess(): Statefull(*new int) {}
~StateLess() { delete &_base_ref; }

你不能没有临时对象,但它们不必在类定义中。

【讨论】:

    【解决方案3】:

    一切都可以通过更多的类来解决

    class StateForStateful
    {
    protected:
        int state;
    };
    
    class Stateless: private StateForStateful, public Stateful // order is important
    {
    public:
         Stateless():Stateful(this->state) {}
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-17
      • 2021-05-28
      • 2016-04-05
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 2015-07-03
      • 2015-10-07
      相关资源
      最近更新 更多