<future> 注释13:比较杂的辅助类 _Allocator_deleter<Alloc>,_Alloc_construct_ptr<Alloc>,函 _Make_unique_alloc ( )

(42) 比较杂的辅助类 _Allocator_deleter,_Alloc_construct_ptr,本篇内容不太重要 。这些类是为了接下来生成 promise 中的数据对象成员,指明该对象成员应该如何构造如何析构。一并给出其代码,以保持代码之间的连贯性:

template <class _Alloc>   // pointer used to help construct 1 _Alloc::value_type without EH
struct _Alloc_construct_ptr
{
    using pointer = _Alloc_ptr_t<_Alloc>;   _Alloc& _Al;    pointer _Ptr;

    explicit _Alloc_construct_ptr(_Alloc& _Al_) : _Al(_Al_), _Ptr(nullptr) {} // 构造函数

    _Alloc_construct_ptr(const _Alloc_construct_ptr&) = delete; // 禁止了 copy 构造函数
    _Alloc_construct_ptr& operator=(const _Alloc_construct_ptr&) = delete; // 禁止 copy 赋值运算符函数

    // disengage *this and return contained pointer
    pointer _Release() noexcept {  return _STD exchange(_Ptr, nullptr);  }

    void _Allocate()  // disengage *this, then allocate a new memory block
    {
        _Ptr = nullptr;  // if allocate throws, prevents double-free
        _Ptr = _Al.allocate(1);
    }

    // if this instance is engaged, deallocate storage
    ~_Alloc_construct_ptr() { if (_Ptr)   _Al.deallocate(_Ptr, 1); }
};

(43) 函 _Make_unique_alloc ( …) 的源代码,此函数返回一个独占型智能指针:

template <class _Alloc>
struct _Allocator_deleter
{
    _Alloc _Al;

    using pointer = typename allocator_traits<_Alloc>::pointer;

    void operator()(pointer _Ptr) noexcept   // delete the pointer
    {
        _Destroy_in_place(*_Ptr);
/*
template <class _Ty>
void _Destroy_in_place(_Ty& _Obj) // 对象的析构函数调用与数组中对象的批量析构
{
    if (is_array_v<_Ty>)     _Destroy_range(_Obj, _Obj + extent_v<_Ty>);
    else                     _Obj.~_Ty();
}
*/
        _Al.deallocate(_Ptr, 1);
    }
};

// template <class _Ty, class _Dx = default_delete<_Ty>>
// class unique_ptr; 可见,对于独占型智能指针,要提供一个对象删除器
template <class _Alloc>  // 本模板类的定义是独占型智能指针的简写形式
using _Unique_ptr_alloc = unique_ptr<typename _Alloc::value_type, _Allocator_deleter<_Alloc>>;

// construct an object with an allocator and return it owned by a unique_ptr
template <class _Alloc, class... _Args> // 用分配器构造一个对象并返回一个unique_ptr所拥有的对象 
_Unique_ptr_alloc<_Alloc>               // 这一行是函数的返回值,类型定义在上面,返回独占型智能指针
_Make_unique_alloc(_Alloc& _Al, _Args&&... _Vals) 
{
    _Alloc_construct_ptr<_Alloc> _Constructor{ _Al };

    _Constructor._Allocate();
    _Construct_in_place( *_Constructor._Ptr, _STD forward<_Args>(_Vals)...);
    return _Unique_ptr_alloc<_Alloc>(_Constructor._Release(), _Allocator_deleter<_Alloc>{_Al});
}

(44)

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值