有什么真正好的理由抛弃std::allocator,转而使用定制的解决方案?您是否遇到过为了正确性、性能、可伸缩性等而绝对需要它的情况?有什么非常聪明的例子吗?
自定义分配器一直是标准库的一个特性,但我并没有太多的需求。我只是想知道这里是否有人能提供一些令人信服的例子来证明它们的存在。
发布于 2009-05-05 19:53:46
正如我提到的here,我已经看到Intel TBB的自定义STL分配器通过简单地更改单个
std::vector<T>至
std::vector<T,tbb::scalable_allocator<T> >(这是一种将分配器切换为使用TBB漂亮的线程私有堆的快速方便的方法;请参阅page 7 in this document)
发布于 2009-05-05 20:01:09
自定义分配器可能有用的一个领域是游戏开发,特别是在游戏控制台上,因为它们只有少量的内存并且没有交换空间。在这样的系统上,您需要确保对每个子系统都有严格的控制,这样一个非关键的系统就不能从一个关键的系统中窃取内存。其他东西,如池分配器,可以帮助减少内存碎片。您可以在以下位置找到一篇关于该主题的长篇、详细的论文:
EASTL -- Electronic Arts Standard Template Library
发布于 2012-09-21 19:06:31
我正在开发一个mmap-allocator,它允许向量使用内存映射文件中的内存。我们的目标是让使用存储的向量通过mmap直接映射到虚拟内存中。我们的问题是提高读取非常大的文件(>10 is )到内存而没有复制开销,因此我需要这个自定义分配器。
到目前为止,我已经有了自定义分配器的框架(它是从std::allocator派生的),我认为这是编写自己的分配器的一个很好的起点。请随意以您想要的方式使用这段代码:
#include <memory>
#include <stdio.h>
namespace mmap_allocator_namespace
{
// See StackOverflow replies to this answer for important commentary about inheriting from std::allocator before replicating this code.
template <typename T>
class mmap_allocator: public std::allocator<T>
{
public:
typedef size_t size_type;
typedef T* pointer;
typedef const T* const_pointer;
template<typename _Tp1>
struct rebind
{
typedef mmap_allocator<_Tp1> other;
};
pointer allocate(size_type n, const void *hint=0)
{
fprintf(stderr, "Alloc %d bytes.\n", n*sizeof(T));
return std::allocator<T>::allocate(n, hint);
}
void deallocate(pointer p, size_type n)
{
fprintf(stderr, "Dealloc %d bytes (%p).\n", n*sizeof(T), p);
return std::allocator<T>::deallocate(p, n);
}
mmap_allocator() throw(): std::allocator<T>() { fprintf(stderr, "Hello allocator!\n"); }
mmap_allocator(const mmap_allocator &a) throw(): std::allocator<T>(a) { }
template <class U>
mmap_allocator(const mmap_allocator<U> &a) throw(): std::allocator<T>(a) { }
~mmap_allocator() throw() { }
};
}要使用它,请声明一个STL容器,如下所示:
using namespace std;
using namespace mmap_allocator_namespace;
vector<int, mmap_allocator<int> > int_vec(1024, 0, mmap_allocator<int>());例如,它可以用来在分配内存时进行日志记录。必需的是重新绑定结构,否则向量容器使用超类分配/释放方法。
更新:内存映射分配器现在可以在https://github.com/johannesthoma/mmap_allocator上使用,并且是LGPL。你可以在你的项目中使用它。
https://stackoverflow.com/questions/826569
复制相似问题