What's the advantage of using std::allocator instead of new in C++?

前端 未结 8 1935
天命终不由人
天命终不由人 2020-12-04 13:14

I\'ve just read about std::allocator. In my opinion, it is more complicated to use it instead of using new and delete.

With <

8条回答
  •  醉梦人生
    2020-12-04 13:42

    Allocators are a very important concept in the STL. Every container is capable to take an allocator as argument. Then allocations will be performed using this allocator, and not the standard one.

    This is useful e.g. for allocating objects of the same size in a pool, to improve performance, or might be necessary if there's a special area of memory where your objects need to live.

    The steps of allocating and constructing are separate because e.g. for vector (std::vector::reserve) it's important to be able to allocate memory for future use, but not (yet) create objects therein.

    As an example you could write an allocator as a class, containing an fixed size array, and use that array to provide memory for some standard container. Then you can have an instance of that class on the stack and thus completely avoid heap allocations for some part of your programm.

    See more examples here in this SO post.

    [...] when should it be used [...]

    When you have specific needs, and most important when writing own generic containers.

提交回复
热议问题