Recently, I became interested in tracking memory allocation and deallocation. When overloading the new and delete operators, I found that the C++ standard library sometimes calls the overloaded operators and sometimes allocates memory using other methods. (Probably std::allocator
.) For instance, std::string
seems not to use new
. Although, std::vector
seems to call new
when push_back
is called. This is surprising since I would think the standard library would have a uniform policy to manage memory allocation.
When does the standard library choose to new
vs std::allocator
? Why?
The standard containers will use the allocator provided to them to allocate dynamic memory. By default, that is std::allocator
.
For most other dynamic memory uses in the standard library, the standard doesn't specify how the implementation should acquire memory, and the implementation has the freedom to do what they want.
As for tracking memory allocations, I recommend wrapping malloc
.