[英]C++14 custom container supporting allocator
我实现了自定义分配器,可以像使用STL容器一样使用它:
std::map<int, int, std::less<int>, CustomAllocator<int,100>> m1;
现在我想创建一个支持这个自定义分配器的自定义容器。 我知道如何在C ++ 17中使用pmr::polymorphic_allocator<byte>
。 所以,假设我们有一些Node
结构和一个自定义slist
容器类,它们存储这些节点。 因此,要使用我们的自定义分配器,我们将在我们的类中创建一个成员:
allocator_type m_allocator;
其中allocator_type的定义如下:
using allocator_type = pmr::polymorphic_allocator<byte>;
在我们需要分配器的slist
方法中,我们可以使用它:
//in insert method, construct new Node to store
m_allocator.construct(...);
我们的客户端代码如下所示:
test_resource tr; // our custom allocator
slist<pmr::string> lst(&tr);
但是我怎样才能在C ++ 11/14中实现同样的目标呢? 我应该在自定义容器中指定什么才能使用CustomAllocator
?
可能最简单的解决方案是遵循标准库的模型,并为容器提供一个模板参数,供其使用的分配器。
当你这样做时,不要忘记标准库(从C ++ 11开始)要求对分配器的所有访问都要通过std::allocator_traits
而不是直接访问allocator对象的成员(因为它可能没有全部)。 您应该这样做,以与设计用于标准库的其他分配器兼容。
作为使用分配器特性的一个例子,考虑这个人为的“容器”:
template <class A>
struct StringContainer
{
std::string *data;
A allocator;
StringContainer(std::string value, A allocator);
~StringContainer();
};
以下是实现构造函数的错误方法:
StringContainer(std::string value, A a) : allocator(a)
{
data = allocator.allocate(sizeof(int));
allocator.construct(data, value);
}
原因是分配器不需要提供construct
成员。 如果他们不提供,则使用new
展示位置。 因此,实现构造函数的正确方法是:
StringContainer(std::string value, A a) : allocator(a)
{
data = std::allocator_traits<A>::allocate(allocator, 1);
std::allocator_traits<A>::construct(allocator, data, value);
}
它是std::allocator_traits<A>::construct
,它负责在A
支持时调用construct
,或者如果不支持则调用new
。
同样,析构函数应该像这样实现:
~StringContainer()
{
std::allocator_traits<A>::destroy(allocator, data);
std::allocator_traits<A>::deallocate(allocator, data, 1);
}
实际上,甚至班级也有些错误地实施了。 data
的类型应该是:
typename std::allocator_traits<A>::pointer data;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.