什么是std::分配器,为什么我需要它
What is std::allocator and why do I need it?
cpp 引用的第一行说"如果没有提供用户指定的分配器,则 std::分配器类模板是所有标准库容器使用的默认分配器...'从给定的示例中,我可以看到它用于根据类型进行一些内存分配:
std::allocator<int> a1; // default allocator for ints
int* a = a1.allocate(1); // space for one int
a1.construct(a, 7); // construct the int
std::cout << a[0] << 'n';
a1.deallocate(a, 1); // deallocate space for one int
但是,我仍然可以做类似的事情:
auto a = std::make_unique<int>(7); // single int usage
如果我想要具有连续访问权限的多个整数,还有一些std
容器。
那么我何时以及为什么需要std::allocator
?
简而言之,能够控制如何分配动态内存很有用。显而易见的答案是 new
和 delete
,但有时人们使用其他类型的内存分配,例如预先分配大量内存并将其分块或仅将堆栈用作内存。
分配器模型通过提供为容器提供内存的函数来抽象这一点。我们并不真正关心我们使用的内存来自哪里,只是在我们需要的时候有足够的内存。
std::allocator
本身使用 new
和 delete
,并且是所有标准库容器的模板默认值。当您不需要任何其他分配模型时,它是默认选择。因此,为了回答您的问题,只要您没有为容器提供另一个分配器,您就会一直使用 std::allocator
。
相关文章:
- 为什么 std::unique 不调用 std::sort?
- 为什么std::valarray不是算术的
- 为什么std::async使用同一个线程运行函数
- 为什么std::isnan 不是 constexpr?
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 为什么 std::function 可以作为 std::not2 的参数?
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 为什么std::互斥需要很长的、非常不规则的时间来共享
- 为什么std::vector比数组慢
- 为什么std::copyable包含std::moveable
- 为什么std::to_string()没有模板化
- 为什么std::vector和std::valarray初始化构造函数不同
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 为什么 std::span 缺少 cbegin 和 cend 方法?
- 为什么 std::itrator 无法访问该函数
- 为什么 std::reduce 需要交换性?
- 为什么 std::equal_to会导致动态分配?
- 为什么 std::绑定错误参数可以成功?
- 为什么 std::lerp 不适用于任何已实现所需操作的类型?
- 为什么 std::next 在以空地图开头馈送时卡住