What is the purpose of std::scoped_allocator_adaptor?

后端 未结 2 1929
北荒
北荒 2020-12-24 06:23

In the C++11 standard we have std::scoped_allocator_adaptor in the dynamic memory management library. What are the most important use cases of this class?

2条回答
  •  执念已碎
    2020-12-24 07:03

    Say you have a stateful arena allocator Alloc with a constructor Alloc(Arena&) that allows some special performance for your application, and say that you use a nested hierarchy of containers like this:

    using InnerCont = std::vector>;    
    using OuterCont = std::vector>>;    
    

    Here, the use of scoped_allocator_adaptor will let you propagate the arena object used to initialize your allocator from the outer to the inner container like this:

    auto my_cont = OuterCont{std::scoped_allocator_adaptor(Alloc{my_arena})};
    

    This achieve greater data locality and lets you pre-allocate one big memory arena my_arena for your entire container hierarchy, rather than only make my_arena available for the outer container, and requiring a loop over all innner containers with another arena for each element at that level.

    The class template is actually a variadic template that gives you fine-grained control about which type of allocator to use in each type of the container hierarchy. Presumably this gives complicated data structures better performance (I must confess I haven't seem different allocators in different levels in action anywhere, but maybe large data centers with multi-million users have a use case here).

提交回复
热议问题