如何使shared_ptr包装类与make_shared一起使用

时间:2015-03-16 10:31:05

标签: c++ c++11 shared-ptr

此问题延伸Customising std::shared_ptr or boost::shared_ptr to throw an exception on NULL dereference

我想要一个行为类似于shared_ptr的类,但在解除引用nullptr时抛出异常。在上面的问题中,建议创建一个包含shared_ptr的包装类,并让该包装器抛出异常。

但是,我还想继续使用make_shared。有没有办法让make_shared与我的(或任何)包装类shared_ptr一起工作?可以按照

的方式运作的东西
checked_shared_ptr<MyClass> csp = make_checked_shared<MyClass>(...);

1 个答案:

答案 0 :(得分:5)

添加合适的构造函数

最简单的解决方案是将构造函数添加到template<class T> class checked_shared_ptr,以便可以使用std::shared_ptr<T>进行初始化,这样可以有效地进行以下编译(并执行预期的操作)。

checked_shared_ptr<MyClass> csp = std::make_shared<MyClass> (...);

示例实施

template<class T>
struct checked_shared_ptr {

  template<
    class U,
    class = decltype (std::shared_ptr<T> (std::shared_ptr<U> {}))
  > checked_shared_ptr (std::shared_ptr<U> const& src)
    : _sptr (src)
  { }

  // ...

  T& operator* () {
    if (_sptr)
      return *_sptr;

    throw std::runtime_error ("nullptr");
  }

  // ...

  std::shared_ptr<T> _sptr;
};

checked_shared_ptr<MyClass> csp = std::make_shared<MyClass> ();


<子> 注意

使用decltype(std::shared_ptr<T> (std::shared_ptr<U>))是因为如果可以将U*转换为T*,构造函数只会参与重载解析。