我想要有如下的类结构:
#include <tr1/memory>
class Interface;
class Impl;
class Impl
{
public:
Impl( std::tr1::weak_ptr< Interface > interface );
private:
std::tr1::weak_ptr< Interface > interface_;
};
class Interface
{
public:
Interface() { impl_ = new Impl( this ); }
private:
std::tr1::shared_ptr< Impl > impl_;
};
Impl::Impl( std::tr1::weak_ptr< Interface > interface )
: interface_(interface)
{}
代码不起作用,因为 weak_ptr 只能从 shared_ptr 构造。我无法在 ctor 中构造 this 的 shared_ptr,因为它会在离开 ctor 时破坏对象。
接口(interface)将由调用者持有为 shared_ptr。实现需要是 shared_ptr,因为它的生命周期比接口(interface)生命周期长。
是否有一种优雅的方式来建立这种关系?
最佳答案
我通过从 Impl 中删除使用 shared_ptr
潜在的问题是接口(interface)是有向无环图中的一个节点。每个节点都知道它的 parent 和 child ,所以实现 Node::addChild( shared_ptr< Node > child ) 是不可能的,因为节点不能作为 weak_ptr 添加到 child 的 parent 。
一种方法是使用 intrusive_ptr,但我现在使用静态 Node::link( shared_ptr< Node > parent, shared_ptr< Node > child ) 方法解决了它。
如果我需要执行类似 enable_shared_from_this 的操作,我可能会在稍后使用 intrusive_ptr。
关于c++ - shared_ptr 的接口(interface)模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6693706/