std::allocator定义于头文件 <memory>,是一个模板类,其定义如下:
template< class T >
struct allocator;

这个类用于分配和释放内存空间,是一个内存管理的类。

此模板类的基本信息,列举如下

成员类型

在这里插入图片描述

成员函数

在这里插入图片描述

一个简单的例子

#include <memory>
#include <iostream>
#include <string> 
int main()
{
    std::allocator<int> a1;   // 实例化一个a1的类对象,它是int 的默认分配器
    int* a = a1.allocate(1);  // 类对象a1开辟一个 int 的空间
    a1.construct(a, 7);       // 类对象a1给 int指针赋值7
    std::cout << a[0] << '\n';
    a1.deallocate(a, 1);      // 类对象a1解分配一个 int 的空间
 
    // string 的默认分配器
    std::allocator<std::string> a2;
    // 2 个 string 的空间
    std::string* s = a2.allocate(2); 
 
    a2.construct(s, "foo");
    a2.construct(s + 1, "bar");
 
    std::cout << s[0] << ' ' << s[1] << '\n';
 
    a2.destroy(s);
    a2.destroy(s + 1);
    a2.deallocate(s, 2);
}

输出:

7
foo bar
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐