【问题标题】:Boost shared_ptr and c++ references. What's wrong here, exactly?提升 shared_ptr 和 c++ 引用。这里到底有什么问题?
【发布时间】:2013-07-25 14:07:32
【问题描述】:

下面的代码是创建一个B的链,由方法f遍历。

如下所示,代码不起作用。每次遍历只深入一层。

我知道链应该只返回一个 shared_ptr,但我的问题是为什么这不起作用?

#include <iostream>
#include <boost/shared_ptr.hpp>

class B
{
public:
  B()
  {
  }

  B(const B& b)
  {
  }

  B& chain()
  {
    b = boost::shared_ptr<B>(new B());

    return *b;
  }

  void f()
  {
    std::cout << this << " " << bool(b) << std::endl;

    if (b)
      return b->f();

    return;
  }

  boost::shared_ptr<B> b;
};

int main()
{
  B b0;
  B b1 = b0.chain();
  B b2 = b1.chain();

  b0.f();
  b1.f();
  b2.f();
}

【问题讨论】:

    标签: c++ boost reference shared-ptr


    【解决方案1】:

    因为当您将其分配给非引用变量b1b2 时,会生成副本。而且由于您有一个不执行任何操作的复制构造函数,因此不会复制成员变量。

    要么删除复制构造函数,要么正确实现它。

    【讨论】:

      猜你喜欢
      • 2010-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 2011-03-02
      • 2021-10-03
      • 1970-01-01
      • 2011-08-16
      相关资源
      最近更新 更多