c++ - shared_ptr 的接口(interface)模式

标签 c++ shared-ptr

我想要有如下的类结构:

#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/

相关文章:

c++ - C++: vector 分配器行为,内存分配和智能指针

c++ - 检查调用shared_from_this()是否有效的方法?

c++ - 为什么 `packaged_task`没有推导指南?

c++ - 语法错误 : EOF in backquote substitution make: *** [mainwindow. o] 错误 2

c++ - 对 Win32 CreateProcess 的困惑

c++ - 使用 std::shared_ptr 而不是 boost::shared_ptr 时编译失败

C++ set 和 shared_ptr

c++ - 关于 shared_from_this 的问题

C++ float 和 valgrind 奇怪的行为

c++ - 如何正确存储/传递接口(interface)类型的变量(现代 C++)?