St::AlcOctor()在C++中的例子

分配器是负责封装内存管理的对象。 分配器 当您希望分两步进行单独分配和构造时,使用。当分两步完成单独的销毁和解除分配时,也会使用它。

null

C++中的所有STL容器都有默认类型的参数分配器 分配器 默认分配器只使用new和delete操作符来获取和释放内存。

宣言:

template <class T> class allocator;

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

  1. 地址: 它用于获取对象的地址,尽管它在C++20中被删除。
  2. 构造: 它用于构造一个对象。它在C++20中也被删除。
  3. 摧毁: 它用于销毁已分配存储中的对象。它在C++20中也被删除。
  4. 最大尺寸: 它返回支持的最大分配大小。它在C++17中被弃用,在中被删除 C++20。
  5. 分配: 用于分配内存。
  6. 取消分配: 用于释放内存。

以下程序说明了上述功能:

项目1:

// C++ program for illustration
// of std::allocator() function
#include <iostream>
#include <memory>
using namespace std;
int main()
{
// allocator for integer values
allocator< int > 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 <iostream>
#include <memory>
#include <string>
using namespace std;
int main()
{
// allocator for string values
allocator<string> 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::分配器的优点

  1. 分配器是STL容器的内存分配器。这个容器可以将内存分配和取消分配与其元素的初始化和销毁分开。因此,一通vec的电话。向量向量的reserve(n)只为至少n个元素分配内存。不会执行每个元素的构造函数。
  2. 分配器可以根据您需要的容器进行调整,例如,您只想偶尔分配的向量。
  3. 相反地 不允许控制调用哪些构造函数,而只是同时构造所有对象。这是std::allocator比new
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享