shared_ptr and cyclic references

谁说我不能喝 提交于 2019-11-28 23:46:32

Yes, you have misinterpreted this. In your example, all the pointers are pointing to the same object, not forming any cycles.

The assignment of p4 to p2 is a no-op, since those pointers were already equal to begin with.

Here's an example with real cyclic references, maybe that will clear things up:

struct A
{
  std::shared_ptr<A> ptr;
};

void main()
{
  std::shared_ptr<A> x=std::make_shared<A>();
  std::shared_ptr<A> y=std::make_shared<A>();

  x->ptr = y; // not quite a cycle yet
  y->ptr = x; // now we got a cycle x keeps y alive and y keeps x alive
}

You can even make this even simpler:

void main()
{
  std::shared_ptr<A> x=std::make_shared<A>();

  x->ptr = x; // never die! x keeps itself alive
}

In both examples, the objects in the shared_ptrs are never destructed, even after you leave main.

Just wanted to point out: the reason why the second line of the output is a 5 and not a 4 is not because of the s->i++ increase, but because the shared_ptr<A> s parameter is being passed by value.

Upon calling

p1 = changeI(p4); // 2) 2nd cyclic ref.

p4 will be copied to yet another shared_pointer, temporarily increasing the use_count by one during the scope of the function.

Maybe I'm playing captain obvious here (;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!