C内存分配器如何实现的动态分配?
摘要:MemorySource 什么是内存分配器 内存分配器就是负责内存的申请和释放的一个"管家"。没有管家时,你要自己管: int* p = new int(42);申请 de
MemorySource
什么是内存分配器
内存分配器就是负责内存的申请和释放的一个"管家"。
// 没有管家时,你要自己管:
int* p = new int(42); // 申请
delete p; // 释放
// 有管家时,你告诉管家:
std::allocator<int> alloc; // 找个管家
int* p = alloc.allocate(1); // 管家去申请
alloc.construct(p, 42); // 管家帮忙构造
alloc.destroy(p); // 管家帮忙析构
alloc.deallocate(p, 1); // 管家去释放
所有的C++标准容器实际上都有分配其参数
// vector 的定义
template<
class T,
class Allocator = std::allocator<T> // 默认分配器
> class vector;
// list 的定义
template<
class T,
class Allocator = std::allocator<T> // 默认分配器
> class list;
// map 的定义
template<
class Key,
class T,
class Compare = less<Key>,
class Allocator = std::allocator<pair<const Key, T>> // 默认分配器
> class map;
// string 的定义
template<
class CharT,
class Traits = char_traits<CharT>,
class Allocator = std::allocator<CharT> // 默认分配器
> class basic_string;
// 日常写法:分配器参数隐藏了
std::vector<int> v1; // 等价于:
std::vector<int, std::allocator<int>> v2; // 这是完整写法
std::list<std::string> l1; // 等价于:
std::list<std::string, std::allocator<std::string>> l2;
std::map<int, std::string> m1; // 等价于:
std::map<int, std::string, std::less<int>,
std::allocator<std::pair<const int, std::string>>> m2;
根据 C++ 标准,std::allocator 通过调用 ::operator new 和 ::operator delete 来获取和释放内存 。这意味着在默认情况下,容器的内存管理最终会落到全局的 new 和 delete 操作符上。
那么什么又是pmr呢?
在早期传统的allocator中,不同的分配器成了类型的“胎记”。也就是说,即使元素的类型相同使用了不同的分配器也不能放在同一个容器中,不能够相互赋值,代码开始变得不通用。
而pmr则把分配器与类型剥离,变成运行时可以切换的对象。
