什么是std::分配器,为什么我需要它

What is std::allocator and why do I need it?

本文关键字:为什么 std 分配器 什么      更新时间:2023-10-16

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

简而言之,能够控制如何分配动态内存很有用。显而易见的答案是 newdelete ,但有时人们使用其他类型的内存分配,例如预先分配大量内存并将其分块或仅将堆栈用作内存。

分配器模型通过提供为容器提供内存的函数来抽象这一点。我们并不真正关心我们使用的内存来自哪里,只是在我们需要的时候有足够的内存。

std::allocator本身使用 newdelete ,并且是所有标准库容器的模板默认值。当您不需要任何其他分配模型时,它是默认选择。因此,为了回答您的问题,只要您没有为容器提供另一个分配器,您就会一直使用 std::allocator