提升shared_ptr和 C++ 引用。这里到底出了什么问题?

Boost shared_ptr and c++ references. What's wrong here, exactly?

本文关键字:什么 问题 这里 shared ptr 引用 C++ 提升      更新时间:2023-10-16

下面的代码是创建一个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();
}

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

请删除复制构造函数,或者正确实现它。