C++ STL allocator vs operator new

后端 未结 2 1325
刺人心
刺人心 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:59

    For general programming, yes you should use new and delete.

    However, if you are writing a library, you should not! I don't have your textbook, but I imagine it is discussing allocators in the context of writing library code.

    Users of a library may want control over exactly what gets allocated from where. If all of the library's allocations went through new and delete, the user would have no way to have that fine-grained level of control.

    All STL containers take an optional allocator template argument. The container will then use that allocator for its internal memory needs. By default, if you omit the allocator, it will use std::allocator which uses new and delete (specifically, ::operator new(size_t) and ::operator delete(void*)).

    This way, the user of that container can control where memory gets allocated from if they desire.

    Example of implementing a custom allocator for use with STL, and explanation: Improving Performance with Custom Pool Allocators for STL

    Side Note: The STL approach to allocators is non-optimal in several ways. I recommend reading Towards a Better Allocator Model for a discussion of some of those issues.

    Edit in 2019: The situation in C++ has improved since this answer was written. Stateful allocators are supported in C++11, and that support was improved in C++17. Some of the people involved in the "Towards a Better Allocator Model" were involved in those changes (eg: N2387), so that's nice (:

提交回复
热议问题