c++ tr1 enable_shared_from_this 有什么好处?

标签 c++ tr1

我目前正在通读 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”是否正常,或者我使用它可能面临的缺点。

最佳答案

enable_shared_from_this 在对象将被共享的类实现中最有用。您希望为对象的所有 shared_ptr 实例共享相同的引用计数器(通常通过复制 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 

关于c++ tr1 enable_shared_from_this 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8174974/

相关文章:

c++ - 使用管道后如何将 std::cin 恢复到键盘?

c++ - C++中python dict和tr1::unordered_map的区别

c++ - 使用 unordered_set 防止不同哈希值的键落入同一个桶

c++ - 为什么 clang 处理这个简单的 std::variant 代码的异常?

c++ - 在循环中更改指针

c++ - 在编译时检查 tr1 数组的大小

c++ - tr1::function 和 tr1::bind

c++ - tr1/normal_distribution : No such file or directory

c++ - 是否可以从新的 int[] 中一次删除一项

C++ 面向对象的基类中虚函数的返回值