[英]Should new C++ code use memory resources instead of allocators?
C++17 will bring us std::pmr::memory_resource
which is a clean interface for allocating and deallocating memory. C++17 将为我们带来std::pmr::memory_resource
,它是一个用于分配和释放内存的干净接口。 Unlike the Allocator concept, it does just that and nothing more.与Allocator概念不同,它仅能做到这一点,仅此而已。 There will also be std::pmr::polymorphic_allocator
which wraps a memory resource into a classical allocator so it can be used with existing containers.还将有std::pmr::polymorphic_allocator
将内存资源包装到经典分配器中,以便它可以与现有容器一起使用。
If I'm about to write a new container (or other memory-hungry) type targeting C++17 and later, should I continue programming against the Allocator concept or rather use the newer and cleaner abstraction directly?如果我要编写一个针对 C++17 及更高版本的新容器(或其他内存饥饿)类型,我应该继续针对分配器概念进行编程还是直接使用更新和更清晰的抽象?
As of now, my thoughts go like this.到目前为止,我的想法是这样的。
Reasons to continue using allocators:继续使用分配器的原因:
std::pmr::*
container aliases continue to use allocators.即使是新的std::pmr::*
容器别名也继续使用分配器。std::pmr::polymorphic_allocator
, the allocator interface is more general and satisfies the needs of more clients.由于可以将内存资源包装到std::pmr::polymorphic_allocator
,因此 allocator 接口更加通用,可以满足更多客户端的需求。Reasons to start using memory resources instead of allocators:开始使用内存资源而不是分配器的原因:
std::pmr::memory_resource
interface is clean and straight-forward. std::pmr::memory_resource
接口简洁明了。std::pmr::polymorphic_allocator
.如果一个对象使用内存资源,它总是可以通过将内存资源包装到std::pmr::polymorphic_allocator
来实例化仍然使用分配器的子对象。 The other way round is more difficult.反过来就更难了。Do there already exist any recommendations for how to use the new library feature effectively?是否已经存在关于如何有效使用新库功能的任何建议?
At this point no.在这一点上没有。
Allocators in C++ currently are much easier than they used to be. C++ 中的分配器目前比以前容易得多。
They provide both pmr (polymorphic) and classic allocator support.它们提供 pmr(多态)和经典分配器支持。
More importantly, pmr based allocation has not been in heavy use for years.更重要的是,基于 pmr 的分配多年来一直没有被大量使用。 Any weaknesses may still come to light.任何弱点都可能会暴露出来。
Fast pool based allocators, or even fixed buffer ones or sbo (small buffer optimization) extensions, may notice the virtualization overhead.基于快速池的分配器,甚至固定缓冲区分配器或 sbo(小缓冲区优化)扩展,可能会注意到虚拟化开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.