gpt4 book ai didi

c++ - 为什么我们需要 enable_shared_from_this

转载 作者:太空宇宙 更新时间:2023-11-03 10:29:47 24 4
gpt4 key购买 nike

<分区>

我正在查看 shared_ptr 和 enable_shared_from_this 的 boost 文档,但我无法弄清楚 enable_shared_from_this 的实际用途。

以下是我对 enable_shared_from_this 的理解(从 What is the usefulness of `enable_shared_from_this`? 复制的例子)。

class Y: public enable_shared_from_this<Y>
{
public:
Y(): count(3){}
shared_ptr<Y> f()
{
return shared_from_this();
}
int count;
}

int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
cout << "\n Count from P is " << p1->count;
cout << "\n Count from q is " << q1->count;
}

所以,现在我们有一个共享指针 q,它指向 p (new Y) 拥有的同一个对象,当 p 和 q 都超出范围时,该对象将被销毁。上面的两个打印语句都会打印 3 作为计数。

现在,我可以通过以下操作在不使用 enable_shared_from_this 的情况下实现相同的目的。

class Y
{
public:
Y(): count(3){}
int count;
}

int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q(p);
cout << "\n Count from P is " << p1->count;
cout << "\n Count from q is " << q1->count;
}

即使在上面的例子中,P 和 Q 都指向同一个对象并打印 3。

那么,使用 enable_shared_from_this 对我有什么好处?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com