【发布时间】:2011-08-09 02:07:15
【问题描述】:
所以我们有(伪代码):
class A
{
A(shared_ptr parent){}
}
class B
{
A *a;
B()
{
a = new A(boost::shared_ptr(this));
}
}
是否可以在 C++ 中使用 shared_ptr 做这样的事情,以及如何在真正的 C++ 代码中做到这一点?
【问题讨论】:
标签: c++ class boost shared-ptr
所以我们有(伪代码):
class A
{
A(shared_ptr parent){}
}
class B
{
A *a;
B()
{
a = new A(boost::shared_ptr(this));
}
}
是否可以在 C++ 中使用 shared_ptr 做这样的事情,以及如何在真正的 C++ 代码中做到这一点?
【问题讨论】:
标签: c++ class boost shared-ptr
你需要enable_shared_from_this:
#include <memory>
class B : public std::enable_shared_from_this<B>
{
A * a;
public:
B() : a(new A(std::shared_from_this())) { }
};
(这是针对 C++0x 的;Boost 应该类似地工作。)
仅仅从this 中创建一个共享指针是很棘手的,因为你可能会把自己的脚踢飞。从enable_shared_from_this 继承使这更容易。
警告:您使用裸A 指针的构造似乎违背了使用资源管理类的目的。为什么不把a 也变成智能指针呢?也许是unique_ptr?
【讨论】: