c++ - 如何使用 C++ 11 样式的非默认可构造分配器指定初始大小?

标签 c++ list c++11 allocator

在关于 Visual Studio 2015 std::list::sort 处理没有默认分配器的列表的更新的先前线程中,这是用于创建此类列表的示例之一,基于在没有默认分配器的 Microsoft 示例中。

我正在尝试弄清楚如何创建具有初始(非零)大小的 std::list 实例,而无需在创建空列表后调整大小。

// this part of the code based on Microsoft example
template <class T>  
struct Mallocator  
{  
    typedef T value_type;  
    Mallocator(T) noexcept {} //default ctor not required by STL  

    // A converting copy constructor:  
    template<class U> Mallocator(const Mallocator<U>&) noexcept {}  
    template<class U> bool operator==(const Mallocator<U>&) const noexcept  
    {  
        return true;  
    }  
    template<class U> bool operator!=(const Mallocator<U>&) const noexcept  
    {  
        return false;  
    }  
    T* allocate(const size_t n) const;  
    void deallocate(T* const p, size_t) const noexcept;  
};  

template <class T>  
T* Mallocator<T>::allocate(const size_t n) const  
{
    if (n == 0)  
    {  
        return nullptr;  
    }  
    if (n > static_cast<size_t>(-1) / sizeof(T))  
    {  
        throw std::bad_array_new_length();  
    }  
    void* const pv = malloc(n * sizeof(T));  
    if (!pv) { throw std::bad_alloc(); }  
    return static_cast<T*>(pv);  
}  

template<class T>  
void Mallocator<T>::deallocate(T * const p, size_t) const noexcept  
{  
    free(p);  
}  

typedef unsigned long long uint64_t;

#define COUNT (4*1024*1024-1)   // number of values to sort

int main(int argc, char**argv)
{
    // this line from a prior answer
    // the (0) is needed to prevent compiler error, but changing the
    // (0) to (COUNT) or other non-zero value has no effect, the size == 0
    std::list <uint64_t, Mallocator<uint64_t>> ll(Mallocator<uint64_t>(0));
    // trying to avoid having to resize the list to get an initial size.
    ll.resize(COUNT, 0);

最佳答案

我尝试了更多变体,触发 Visual Studio 显示参数的各种组合,12 个变体中的第 12 个以正确的顺序显示了参数:(计数、值、分配器)。请注意,在 VS 2015 的情况下,没有 (count, allocator) 的选项,需要包含该值。最后一个参数 (0) 中的值并不重要,它只需要是正确的类型即可。

    std::list <uint64_t, Mallocator<uint64_t>> ll(COUNT, 0, Mallocator<uint64_t>(0));

关于c++ - 如何使用 C++ 11 样式的非默认可构造分配器指定初始大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56072806/

相关文章:

c++ - 显式类模板实例化的链接

c++ - 启动多个线程 - 实例化错误 (C++)

c# - Windows 中文件的全局唯一 ID

c++ - 调用外部代码

c++ - 单元测试没有失败但卡在子程序调用上

python - 如何删除嵌套列表中的重复项?

C++ - 在类上使用 &String[0] 访问 char*

c# - 列表与数组 : One-To-Many and Has-A Relationship

javascript - CheckBoxList 控件在回发后丢失所有项目

c++ - 使用 move 赋值运算符分配刚构造的未命名值