【问题标题】:c++ tr1 enable_shared_from_this what's the advantage?c++ tr1 enable_shared_from_this 有什么好处?
【发布时间】:2011-11-17 22:00:23
【问题描述】:

我目前正在阅读 C++ TR1 扩展并开始关注 std::tr1::shared_ptr。

所以,到目前为止,我可以使用以下代码声明和初始化 shared_ptr:

class foo {};
std::tr1::shared_ptr<foo> fsp(new foo);
std::tr1::shared_ptr<foo> fps2(fsp);    // (1) init using first sp

现在我读到了 enable_shared_from_this (http://msdn.microsoft.com/en-us/library/bb982611%28v=VS.90%29.aspx) 并看到了这个例子:

class foo : public enable_shared_from_this<foo> {};
std::tr1::shared_ptr<foo> fsp(new foo);
std::tr1::shared_ptr<foo> fps2 = fsp->shared_from_this(); // (2) init using first sp

我的问题是,与我标记为“(1) init using first sp”的初始化相比,我为什么要使用 shared_from_this。

我已经阅读了What is the usefulness of `enable_shared_from_this`? 的文章,现在更好地理解了它的用处。

但这让我敞开心扉,无论我的“(1) init using first sp”是否可以,或者我使用它可能面临什么缺点。

【问题讨论】:

  • 你能把你的问题精简为......你的实际问题吗?很高兴你今天学到了一些东西,但这与问题无关。
  • 我认为由于缺乏使用 shared_ptr 的经验,每个回答的问题都会揭示下一个问题。 K-Ballo 的回答证实(1)实际上是可以的。 Andy T 的回答立即回答了我脑海中突然出现的问题(我在哪里需要 enable_shared_from_this)。

标签: c++ tr1


【解决方案1】:

enable_shared_from_this 在对象将被共享的类实现中最有用。您希望为对象的所有shared_ptrs 实例共享相同的引用计数器(通常通过复制shared_ptr 来完成),但类实现没有任何复制。在这种情况下,您可以使用shared_from_this

考虑:

struct A;

void f(shared_ptr<A> const&) {...}

struct A: public enable_shared_from_this<A>
{
    void a_f()
    {
        // you need to call f() here passing itself as a parameter
        f(shared_from_this());
    }
};

shared_ptr<A> a_ptr(new A());
a_ptr->a_f(); // in inner call to f() will be used temporary shared_ptr<A> 
// that uses (shares) the same reference counter as a_ptr 

【讨论】:

  • +1 第 2 句解释得非常清楚:You want to share [...] by copying shared_ptr, but [...] implementation doesn't have any to make a copy from
  • 啊,现在我明白了 enable_shared_from_this 的真正需要。谢谢。
【解决方案2】:

AFAIK 你的陈述 (1) 没问题。 enable_shared_from_this 是关于从对象中获取shared_ptr,如果您已经拥有shared_ptr,那么您不需要调用它。

【讨论】:

    猜你喜欢
    • 2010-09-16
    • 2010-09-16
    • 1970-01-01
    • 2021-07-25
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多