memory - C++ STL allocator vs operator new -


according c++ primer 4th edition, page 755, there note saying:

modern c++ programs ordinarily ought use allocator class allocate memory. safer , more flexible.

i don't quite understand statement. far materials read teach using new allocate memory in c++. example of how vector class utilize allocator shown in book. however, cannot think of other scenarios.

can clarify statement? , give me more examples? when should use allocator , when use new? thanks!

for general programming, yes should use new , delete.

however, if writing library, should not! don't have textbook, imagine discussing allocators in context of writing library code.

users of library may want control on gets allocated where. if of library's allocations went through new , delete, user have no way have fine-grained level of control.

all stl containers take optional allocator template argument. container use allocator internal memory needs. default, if omit allocator, use std::allocator uses new , delete (specifically, ::operator new(size_t) , ::operator delete(void*)).

this way, user of container can control memory gets allocated if desire.

example of implementing custom allocator use stl, , explanation: improving performance custom pool allocators stl

side note: stl approach allocators non-optimal in several ways. recommend reading towards better allocator model discussion of of issues.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -