简体   繁体   English

Memory在C++标准库中的分配

[英]Memory allocation in the C++ standard library

Recently, I became interested in tracking memory allocation and deallocation.最近,我对跟踪 memory 的分配和释放产生了兴趣。 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.在重载new和delete运算符时,我发现C++标准库有时会调用重载的运算符,有时会使用其他方法分配memory。 (Probably std::allocator .) For instance, std::string seems not to use new . (可能是std::allocator 。)例如, std::string似乎不使用new Although, std::vector seems to call new when push_back is called.虽然,当调用push_back时, std::vector似乎调用了new This is surprising since I would think the standard library would have a uniform policy to manage memory allocation.这是令人惊讶的,因为我认为标准库将有一个统一的策略来管理 memory 分配。

When does the standard library choose to new vs std::allocator ?标准库什么时候选择new vs std::allocator Why?为什么?

The standard containers will use the allocator provided to them to allocate dynamic memory.标准容器将使用提供给它们的分配器来分配动态 memory。 By default, that is std::allocator .默认情况下,即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.对于标准库中使用的大多数其他动态 memory,标准并没有指定实现应该如何获取 memory,并且实现可以自由地为所欲为。


As for tracking memory allocations, I recommend wrapping malloc .至于跟踪 memory 分配,我建议包装malloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM