为什么我们要使用std::alloctor

引言

我们在初学C++的时候会学到std::alloctor这么一个东西,看着其奇怪的内存分配难免使人失去了看下去的欲望,原因就是不知道这个东西到底有什么用,笔者收集了一些资料,通过这篇文章简单的谈谈它的作用

Google
std::allocator is used when you want to separate allocation and do
construction in two steps. It is also used when separate destruction
and deallocation is done in two steps. All the STL containers in C++
have a type parameter Allocator that is by default std::allocator.

通过这段解释我认为认为alloctor完全可以当做一个对象池来使用 因为其可以分离构造与分配 在需要高性能的场合显然效率较高(减少系统调用和不必要的构造) 虽然相比与boot::pool中的object_pool 其少了GC (object_pool因为其效率广为诟病)

我们再来看一段解释

What’s the advantage of using std::allocator instead of new in C++?
std::allocator is the default memory allocator for the standard library containers, and you can substitute your own allocators. This allows you to control how the standard containers allocate memory. But I don’t think that your question is about std::allocator specifically, but rather the strategy of allocating memory, then constucting objects in that memory, rather than using new T[N], for example.
And the reason for that is that new T[N] doesn’t allow you control over what constructors are called. And it forces you to construct all your objects at the same time. This is terrible for the purposes of, for example, std::vector where you only want to allocate occasionally.
With a raw memory allocator, you can allocate a certain amount of memory, which determines your capacity. Then, as the user adds items to the vector (using the constructor of their choice), you can construct objects in place in this memory.
Then when you run out of memory, you allocate more, typically twice as much. If std::vector used new T[N], it would have to reallocate every time you wanted to add or remove an element, which would be terrible for performance. You would also be forced to use the default constructor for all the objects, which puts an unnecessary restriction on the types of objects std::vector can hold.

std::alloctor是标准库容器默认的内存分配器,你也可以替换为你自己的分配器(比如boost中的pool_allocator),这允许你控制容器的内存分配,但是我不认为你的问题是关于std::alloctor的,而是内存分配后在在这个内存中构造对象的策略,而不是去使用new,举个例子.
这件事情的原因就是new不允许你控制何时构造,它会强迫你同时构造所有的对象,出于以下目的这是很糟糕的,对于std::vector你只想构造一部分.
对于原始的的内存分配,你可以分配确定数量的内存,它们决定了你的容量,接着,当使用者向vector添加元素时(使用他们所选择的构造函数),你可以在此内存中构造对象,
当你内存不足的时候,你可以分配更多,通常是两倍,如果std::vector使用new,它将不得不在每一次你想添加或删除元素时进行reallocate,这是个极大的效率损耗,你将被强迫对所有的对象使用默认构造函数,这对于std::vector的元素来说也是一个不必要的限制.

通过这两段解释 我觉得alloctor最大的作用就是可以使我们分离分配与构造 但有一点很重要
在这里插入图片描述
construct 与 destory 在C++20中均被移除.

参考:
stackoverflow

发布了93 篇原创文章 · 获赞 69 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43705457/article/details/103541290