在the raw-pointer constructor of shared_ptr
中,一个unique_ptr
__hold
用于保存参数__p
,然后在没有任何访问的情况下释放?有什么用?
template<class _Yp, class = _EnableIf< /*...*/ > >
explicit shared_ptr(_Yp* __p) : __ptr_(__p) {
unique_ptr<_Yp> __hold(__p); // <--- created
typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
typedef __shared_ptr_pointer<_Yp*, __shared_ptr_default_delete<_Tp, _Yp>, _AllocT > _CntrlBlk;
__cntrl_ = new _CntrlBlk(__p, __shared_ptr_default_delete<_Tp, _Yp>(), _AllocT());
__hold.release(); // <--- released
__enable_weak_this(__p, __p);
}
答案 0 :(得分:2)
为什么 libc++ 的 shared_ptr 实现使用 unique_ptr 来保存原始指针构造函数中的原始指针?
unique_ptr
用于通常使用唯一指针的目的:当指针超出范围时删除指针。在这种情况下,唯一指针总是在构造函数正常返回之前被释放,在这种情况下它不会删除指针。但是当抛出异常时不会发生这种情况。在那种情况下,唯一指针仍将拥有该指针,并将在异常传播到调用者之前在其析构函数中删除它。