C++ STL allocator vs operator new

后端 未结 2 1312
刺人心
刺人心 2021-01-30 11:32

According to C++ Primer 4th edition, page 755, there is a note saying:

Modern C++ programs ordinarily ought to use the allocator class to allocate memor

2条回答
  •  北海茫月
    2021-01-30 11:35

    The two are not contradictory. Allocators are a PolicyPattern or StrategyPattern used by the STL libraries' container adapters to allocate chunks of memory for use with objects.

    These allocators frequently optimize memory allocation by allowing * ranges of elements to be allocated at once, and then initialized using a placement new * items to be selected from secondary, specialized heaps depending on blocksize

    One way or another, the end result will (almost always) be that the objects are allocated with new (placement or default)


    Another vivid example would be how e.g. boost library implements smartpointers. Because smartpointers are very small (with little overhead) the allocation overhead might become a burden. It would make sense for the implementation to define a specialized allocator to do the allocations, so one may have efficient std::set<> of smartpointers, std::map<..., smartpointer> etc.

    (Now I'm almost sure that boost actually optimizes storage for most smartpointers by avoiding any virtuals, therefore the vft, making the class a POD structure, with only the raw pointer as storage; some of the example will not apply. But then again, extrapolate to other kinds of smartpointer (refcounting smartpointers, pointers to member functions, pointers to member functions with instance reference etc. etc.))

提交回复
热议问题