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

猜你喜欢

转载自blog.csdn.net/thefist11cc/article/details/123931359