简体   繁体   English

shared_ptr和循环引用

[英]shared_ptr and cyclic references

I was trying with the cyclic references for boost::shared_ptr , and devised following sample: 我正在尝试使用boost::shared_ptr的循环引用,并设计了以下示例:

class A{ // Trivial class
public:
    i32 i;
    A(){}
    A(i32 a):i(a){}
    ~A(){
        cout<<"~A : "<<i<<endl;
    }
};

shared_ptr<A> changeI(shared_ptr<A> s){
    s->i++;
    cout<<s.use_count()<<'\n';

    return s;
}

int main() {

    shared_ptr<A> p1 = make_shared<A>(3);
    shared_ptr<A> p2 = p1;
    shared_ptr<A> p3 = p2;
    shared_ptr<A> p4 = p3;

    p1 = p4; // 1) 1st cyclic ref.
    cout<<p1.use_count()<<'\n';

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

    cout<<p1.use_count()<<'\n';

//  putchar('\n');
    cout<<endl;
}

which outputs 哪个输出

4
5
4

~A : 4

Is it that I've misinterpreted the cyclic references mentioned for boost::shared_ptr ? 是不是我误解了为boost::shared_ptr提到的循环引用? Because, I expected different output thinking of indirect references to p1 after comments 1) and 2) . 因为,我期望在评论1)2)之后对p1的间接引用有不同的输出思路。 So this code doesn't require boost::weak_ptr ! 所以这段代码不需要boost::weak_ptr So what are the cyclic references where weak_ptr s would be required? 那么需要weak_ptr的循环引用是什么?

Thanks in advance. 提前致谢。

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. 将p4赋值给p2是无操作,因为那些指针已经等于开头。

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. 在这两个示例中,即使在离开main之后,shared_ptrs中的对象也永远不会被破坏。

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. 只是想指出:输出的第二行是5而不是4原因不是因为s->i++增加,而是因为shared_ptr<A> s参数是通过值传递的。

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. p4将被复制到另一个shared_pointer ,在函数范围内暂时将use_count增加1。

Maybe I'm playing captain obvious here (; 也许我在这里扮演明显的队长(;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM