这个问题扩展了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>(...);
最佳答案
添加合适的构造函数
最简单的解决方案是向 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*
.
关于c++ - 如何使 shared_ptr 包装类与 make_shared 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29074577/