c++ - boost shared_ptr 运算符 =

标签 c++ boost shared-ptr

这里是代码示例

class A{
  int i;
public:
  A(int i) : i(i) {}
  void f() { prn(i); }
};

int main()
{
  A* pi = new A(9);
  A* pi2= new A(87);
  boost::shared_ptr<A> spi(pi);
  boost::shared_ptr<A> spi2(pi2);
  spi=spi2;
  spi->f();
  spi2->f();
  pi->f();
  pi2->f();
}

输出:

87
87
0
87

问题是为什么输出中是0?

文档注释:效果:等同于 shared_ptr(r).swap(*this)。

但是如果 shared_ptr 对象刚刚交换,结果应该是 9。如果第一个对象被删除,应该有 Segmentation fault。

那为什么是 0?

最佳答案

请注意正在交换的内容:

shared_ptr(r).swap(*this)
// ^^^^^^^^^^

这是一个从 r 构造的临时对象。临时对象立即超出范围并消亡,无论这对拥有的资源有何影响。由于在您的代码中 spi*spi 的唯一所有者,因此该对象被删除,您随后对 pi->f() 的访问只是未定义的行为。

关于c++ - boost shared_ptr 运算符 =,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10048256/

相关文章:

c++ - 在没有 RValue 隐式转换的情况下正确实现

c++ - 缓冲区溢出?

c++ - 快速计算数组中零值字节的数量

具有 3rd 方依赖性的 C++ 开发流程

c++ - io_service 截止时间计时器不定期工作

c++ - shared_ptr 与 scoped_ptr

c++ - 我可以使用什么库来配置大部分或所有 GigE 和/或 Camera Link 相机?

c++ - 随机数类内初始化

c++ - boost::circular_buffer 是否确认自动弹出操作

c++ - 对 shared_ptr 的引用的 reinterpret_cast