什么是enable_shared_from_this的用处 [英] what is the usefulness of enable_shared_from_this

查看:133
本文介绍了什么是enable_shared_from_this的用处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到 enable_shared_from_this 跑一边读Boost.Asio的例子和阅读,我还是失去了这个应该怎么正确使用的文档后。是否有人可以给我使用这个类时的一个例子和/或与解释是有道理的。

I ran across enable_shared_from_this while reading the Boost.Asio examples and after reading the documentation I am still lost for how this should correctly be used. Can someone please give me an example and/or and explanation of when using this class makes sense.

推荐答案

它使您能够得到一个有效的的shared_ptr 实例这个,当你已经是这个。没有它,你就没有得到一个的shared_ptr 这个,除非你已经有一个作为成员的方式。从enable_shared_from_this的 Boost文档这个例子的:

It enables you to get a valid shared_ptr instance to this, when all you have is this. Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member. This example from the boost documentation for enable_shared_from_this:

class Y: public enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_from_this();
    }
}

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership
}

该方法f()的返回一个有效的的shared_ptr ,即使它没有成员实例。需要注意的是,你不能简单地做到这一点:

The method f() returns a valid shared_ptr, even though it had no member instance. Note that you cannot simply do this:

class Y: public enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_ptr<Y>(this);
    }
}

共享指针,这回将有来自正确的一个不同的引用计数,和其中一人将最终失去并保持当对象被删除悬空引用。

The shared pointer that this returned will have a different reference count from the "proper" one, and one of them will end up losing and holding a dangling reference when the object is deleted.

enable_shared_from_this 将是新的C ++ 0x标准的一部分一样,所以你也可以从那里,以及从升压得到它。

enable_shared_from_this is going to be a part of the new C++0x standard as well, so you can also get it from there as well as from boost.

这篇关于什么是enable_shared_from_this的用处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆