我目前正在通读 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/