C++ 库 - <scoped_allocator>



C++ 中的<scoped_allocator> 提供了类和实用程序,允许对内存分配进行高级控制,尤其是在处理嵌套或组合容器时。它用于处理容器本身包含其他容器的情况下的内存分配。它确保嵌套容器中的所有对象共享一个通用的内存分配。

<scoped_allocator> 包含名为 scoped_allocator_adaptor 的类。它允许将分配器参数转发到多个级别的容器,确保外部容器和嵌套容器都可以使用相同的分配器。

包含 <scoped_allocator> 头文件

要在 C++ 程序中包含 <scoped_allocator> 头文件,可以使用以下语法。

#include <scoped_allocator>

<scoped_allocator> 头文件的函数

以下是 <scoped_allocator> 头文件中所有函数的列表。

序号 函数及描述
1 operator=

它赋值一个 scoped_allocator_adaptor。

2 inner_allocator

它获取一个 inner_allocator 引用。

3 outer_allocator

它获取一个 output_allocator 引用。

4 allocate

它使用外部分配器分配未初始化的存储空间。

5 deallocate

它使用外部分配器释放存储空间。

6 max_size

它返回外部分配器支持的最大分配大小。

7 construct

它在已分配的存储空间中构造一个对象。

8 destroy

它在已分配的存储空间中销毁一个对象。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

非成员函数

序号 函数及描述
1 operator==

它比较两个 scoped_allocator_adaptor 实例。

2 operator!=

它比较两个 scoped_allocator_adaptor 实例。

创建作用域分配器

在下面的示例中,我们将创建一个采用标准分配器的 scoped_allocator_adaptor。

Open Compiler
#include <iostream> #include <vector> #include <memory> #include <scoped_allocator> int main() { std::scoped_allocator_adaptor < std::allocator < int >> b; std::vector < std::vector < int, std::allocator < int >> , std::scoped_allocator_adaptor < std::allocator < std::vector < int >>> > x(3, std::vector < int > (5, 0), b); for (int y = 0; y < 2; ++y) { for (int z = 0; z < 4; ++z) { x[y][z] = y * 4 + z; } } for (const auto & a: x) { for (const auto & val: a) { std::cout << val << " "; } std::cout << std::endl; } return 0; }

输出

如果运行上述代码,它将生成以下输出:

0 1 2 3 0 
4 5 6 7 0 
0 0 0 0 0

嵌套容器中的内存管理

考虑下面的示例,我们将使用 std::scoped_allocator_adaptor 在嵌套容器中分配和管理内存。

Open Compiler
#include <iostream> #include <vector> #include <memory> #include <scoped_allocator> int main() { using x = std::allocator < int > ; using y = std::scoped_allocator_adaptor < x > ; std::vector < std::vector < int, x > , y > z(3, std::vector < int > (3)); for (int a = 0; a < 3; ++a) { for (int b = 0; b < 3; ++b) { z[a][b] = a * b; } } for (const auto & row: z) { for (const auto & val: row) { std::cout << val << " "; } std::cout << std::endl; } return 0; }

输出

以下是上述代码的输出:

0 0 0 
0 1 2 
0 2 4
广告