rand1925
rand1925

Reputation: 31

Why does libc++'s implementation of shared_ptr use a unique_ptr to hold the raw pointer in the raw-pointer constructor?

In the raw-pointer constructor of shared_ptr, a unique_ptr __hold is used to hold the argument __p and then released without any visit? What's the usage of it?

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);
}

Upvotes: 1

Views: 195

Answers (1)

eerorika
eerorika

Reputation: 238401

Why does libc++'s implementation of shared_ptr use a unique_ptr to hold the raw pointer in the raw-pointer constructor?

unique_ptr is used for the purpose that unique pointer is typically used: To delete the pointer when it goes out of scope. In this case, the unique pointer is always released before the constructor returns normally and in that case it won't delete the pointer. But that won't happen when an exception is thrown. In that case the unique pointer will still own the pointer and will delete it in its destructor before the exception propagates to the caller.

Upvotes: 4

Related Questions