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

前端 未结 8 1984
天命终不由人
天命终不由人 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:31

    You are confused. std::allocator calls/uses new and delete. It is simply another level in the C++ memory hierarchy, used to serve the various needs of the C++ standard library, particularly the containers, but other types too. The C++ library containers use the allocator to automatically manage the memory of the contained elements. Without it, things would be more cumbersome and thus more difficult to use. Furthermore an allocator can be used to perform different techniques of memory management, eg stack allocation, linear allocation, heap allocation, pool allocation etc.

    C++ memory "hierarchy"

    _________________
    |Applications   |
    |_______________|
          |
    ______↓_______________________
    |C++ library (std::allocator)|
    |____________________________|
          |
    ______↓______________________________________________________________________________
    |C++ primitives (new/delete, new[]/delete[], ::operator new()/::operator delete())  |
    |___________________________________________________________________________________|
          |
    ______↓______
    |malloc/free|
    |___________|
          |
    ______↓______________
    |OS APIs, syscalls  |
    |___________________|
    

    This is the normal flow of calls, but an application can instead call malloc/free, or new/delete or even the OS APIs directly. You see it's ALL an abstraction. The level above abstracts the more difficult nature of the one and wraps it in an easier to use package.

提交回复
热议问题