【发布时间】:2021-07-15 04:45:35
【问题描述】:
在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);
}
【问题讨论】:
-
如果在到达
__hold.release()之前抛出异常会发生什么? -
正如this answer 所说,如果抛出异常,它可以防止内存泄漏。
标签: c++ c++11 llvm clang++ libc++