Moss Richardson
Moss Richardson

Reputation: 286

Memory allocation in the C++ standard library

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?

Upvotes: 5

Views: 1085

Answers (1)

eerorika
eerorika

Reputation: 238461

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.

Upvotes: 3

Related Questions