首页 > 解决方案 > 为什么我必须为分配器的一个实例分配一个值?

问题描述

我从这个链接中得到了关于数组分配器的代码,我在下面显示了关键代码,对于这个问题,我已经删除了构造函数部分,但是我真的不知道为什么我必须ra*this??分配值 如果我只是写ra(),那将是错误的!

在我看来,因为类array_allocator继承自std::allocator<T>,而 的复制构造函数std::allocator什么都不做。

什么是类型ra?我注意到c++17和c++2a中的类型不同,因为在c++2a中“ rebind”结构已经被删除了,所以在之前的版本中类型是std::allocator<int>,但是在c++ 2a中,类型是array_allocator<int>. 作为演示节目。那么这会影响结果吗?我很困惑,对不起我的混乱逻辑。欢迎任何答案:)

#include <memory>
#include <type_traits>
template <typename T>
struct array_allocator : std::allocator<T>
{
    template <typename C, typename ...Args>
    typename std::enable_if<std::is_array<C>::value>::type destroy(C * p)
    {
        using U = typename std::remove_extent<C>::type;
        using UAT = typename std::allocator_traits<array_allocator>::template rebind_traits<U>;
        typename std::allocator_traits<array_allocator>::template rebind_alloc<U> ra(*this);  ???

        for (std::size_t i = 0, e = std::extent<C>::value; i != e; ++i)
        {
            UAT::destroy(ra, std::addressof((*p)[e - i - 1]));
        }
    }

    template <typename C, typename ...Args>
    typename std::enable_if<!std::is_array<C>::value>::type destroy(C * p)
    {
        p->~C();
    }
};

标签: c++traitsallocationallocator

解决方案


推荐阅读