c++新特性11 (10)shared_ptr六”构造函数unique_ptr参数“

Posted thefist11

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++新特性11 (10)shared_ptr六”构造函数unique_ptr参数“相关的知识,希望对你有一定的参考价值。

1. 构造函数

shared_ptr p(u)

p从unique_ptr u中接管了对象的所有权;将u置为空

template <class _Ux, class _Dx,
        enable_if_t<conjunction_v<_SP_pointer_compatible<_Ux, _Ty>,
                        is_convertible<typename unique_ptr<_Ux, _Dx>::pointer, element_type*>>,
            int> = 0>
    shared_ptr(unique_ptr<_Ux, _Dx>&& _Other) 
        using _Fancy_t   = typename unique_ptr<_Ux, _Dx>::pointer;
        using _Raw_t     = typename unique_ptr<_Ux, _Dx>::element_type*;
        using _Deleter_t = conditional_t<is_reference_v<_Dx>, decltype(_STD ref(_Other.get_deleter())), _Dx>;

        const _Fancy_t _Fancy = _Other.get();

        if (_Fancy) 
            const _Raw_t _Raw = _Fancy;
            const auto _Rx    = new _Ref_count_resource<_Fancy_t, _Deleter_t>(_Fancy, _Other.get_deleter());
            _Set_ptr_rep_and_enable_shared(_Raw, _Rx);
            _Other.release();//将u置为空
        
    

1.1 _Ref_count_resource

// CLASS TEMPLATE _Ref_count_resource
template <class _Resource, class _Dx>
class _Ref_count_resource : public _Ref_count_base  // handle reference counting for object with deleter
public:
    _Ref_count_resource(_Resource _Px, _Dx _Dt)
        : _Ref_count_base(), _Mypair(_One_then_variadic_args_t, _STD move(_Dt), _Px) 

#ifdef __EDG__ // TRANSITION, VSO-1292293
    virtual ~_Ref_count_resource() noexcept override  // TRANSITION, should be non-virtual
#else // ^^^ workaround / no workaround vvv
    virtual ~_Ref_count_resource() noexcept override = default; // TRANSITION, should be non-virtual
#endif // ^^^ no workaround ^^^

    virtual void* _Get_deleter(const type_info& _Typeid) const noexcept override 
#if _HAS_STATIC_RTTI
        if (_Typeid == typeid(_Dx)) 
            return const_cast<_Dx*>(_STD addressof(_Mypair._Get_first()));
        
#else // _HAS_STATIC_RTTI
        (void) _Typeid;
#endif // _HAS_STATIC_RTTI

        return nullptr;
    

private:
    virtual void _Destroy() noexcept override  // destroy managed resource
        _Mypair._Get_first()(_Mypair._Myval2);
    

    virtual void _Delete_this() noexcept override  // destroy self
        delete this;
    

    _Compressed_pair<_Dx, _Resource> _Mypair;
;

以上是关于c++新特性11 (10)shared_ptr六”构造函数unique_ptr参数“的主要内容,如果未能解决你的问题,请参考以下文章

c++新特性11 (10)shared_ptr八”shared_ptr类“

c++新特性11 (10)shared_ptr三”创建计数器“

c++新特性11 (10)shared_ptr七reset

c++新特性11 (10)shared_ptr四”_Ptr_base 类“

c++新特性11 (10)shared_ptr五”构造函数“

c++新特性11 (10)shared_ptr二”_Ref_count_base类“