如何使用C 11样式非默认构造分配器指定初始大小
How to specify an initial size using C++ 11 style non-default-constructible allocator?
在关于更新Visual Studio 2015 std::list::sort
的先前线程中没有默认分配器。
我试图弄清楚如何创建具有初始(非零(大小的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);
我在此尝试了更多变化,这些变体触发了视觉工作室以显示参数的各种组合,而12中的12个中的12个均以正确的顺序显示了参数:(计数,值,分析器(。请注意,在VS 2015的情况下,没有任何选项(计数,分析(需要包括该值。最后一个参数中的值,&lt; uint64_t&gt;(0(,并不重要,它只需要是正确的类型。
std::list <uint64_t, Mallocator<uint64_t>> ll(COUNT, 0, Mallocator<uint64_t>(0));
相关文章:
- 将 std::allocate_shared 与多态资源分配器一起使用
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 使用 std::分配器在 constexpr 中进行默认初始化
- 使用不兼容的分配器复制分配无序列图
- 是否可以使用分配器对象来释放另一个分配器分配的内存?
- 使用模板化分配器和对向量进行排序的函数
- 为什么 std::vector 使用 std::分配器而不是运算符 new 和 delete?
- 我可以对 std::array 使用自定义分配器来获取安全加密密钥吗?
- 使用boost void分配器是一种糟糕的做法吗
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 对 std::regex_match 使用自定义分配器
- 如何将分配器与 std::set 一起使用?
- 在调用中使用 std::vector,<double>但收到有关 std::vector<double、std::分配器>正在使用的错误<double>
- 将运算符new和运算符delete与自定义内存池/分配器一起使用
- 如何测试分配器是否使用std::allocate进行内存分配
- 与自定义分配器一起使用的最佳唯一指针是什么
- 将 std::unique_ptr 与自定义分配器一起使用,以包装原始指针
- 在分配器中使用new函数和*alloc函数时,它们之间有区别吗
- 将std::uninitialized_fill()与任何分配器一起使用有意义吗
- 将std::uniqueptr与分配器一起使用