📜  C++中的std :: allocator()示例

📅  最后修改于: 2021-05-30 16:46:59             🧑  作者: Mango

分配器是负责封装内存管理的对象。当您要分离分配并分两步进行构造时,可以使用std :: allocator 。当分两步完成销毁和重新分配时,也可以使用它。

C++中的所有STL容器都有一个类型参数Allocator,默认情况下为std :: allocator 。默认分配器仅使用new和delete运算符来获取和释放内存。

宣言 :

template  class allocator;

与std :: allocator()关联的成员函数:

  1. address:尽管在C++ 20中已将其删除,但它用于获取对象的地址。
  2. 构造:用于构造一个对象,在C++ 20中也将其删除。
  3. destroy:用于销毁已分配存储中的对象,并且在C++ 20中也已删除。
  4. max_size:返回最大支持的分配大小.C++ 17中已弃用,并在C++ 17中将其删除
    C++ 20。
  5. 分配:用于分配内存。
  6. deallocate:用于内存的重新分配。

下面的程序说明了上述函数:

程序1:

// C++ program for illustration
// of std::allocator() function
#include 
#include 
using namespace std;
int main()
{
  
    // allocator for integer values
    allocator myAllocator;
  
    // allocate space for five ints
    int* arr = myAllocator.allocate(5);
  
    // construct arr[0] and arr[3]
    myAllocator.construct(arr, 100);
    arr[3] = 10;
  
    cout << arr[3] << endl;
    cout << arr[0] << endl;
  
    // deallocate space for five ints
    myAllocator.deallocate(arr, 5);
  
    return 0;
}
输出:
10
100

程式2:

// C++ program for illustration
// of std::allocator() function
#include 
#include 
#include 
using namespace std;
  
int main()
{
  
    // allocator for string values
    allocator myAllocator;
  
    // allocate space for three strings
    string* str = myAllocator.allocate(3);
  
    // construct these 3 strings
    myAllocator.construct(str, "Geeks");
    myAllocator.construct(str + 1, "for");
    myAllocator.construct(str + 2, "Geeks");
  
    cout << str[0] << str[1] << str[2];
  
    // destroy these 3 strings
    myAllocator.destroy(str);
    myAllocator.destroy(str + 1);
    myAllocator.destroy(str + 2);
  
    // deallocate space for 3 strings
    myAllocator.deallocate(str, 3);
}
输出:
GeeksforGeeks

使用std :: allocator的优势

  1. 分配器是STL容器的内存分配器。该容器可以将内存分配和取消分配与它们的元素的初始化和销毁分开。因此,调用向量vec的vec.reserve(n)仅为至少n个元素分配内存。每个元素的构造函数都不会执行。
  2. 可以根据您需要的容器来调整分配器,例如,您只希望偶尔分配的向量。
  3. 相反,new不允许控制调用哪些构造函数,而只能同时构造所有对象。这是std :: allocator相对于new的优点
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”