下面的代码是创建一个 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();
}
最佳答案
因为当您将其分配给非引用变量 b1
和 b2
时,会生成拷贝。由于您有一个什么都不做的复制构造函数,因此不会复制成员变量。
要么删除复制构造函数,要么正确实现它。
关于c++ - boost shared_ptr 和 c++ 引用。这里到底出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17860351/