C++ Library - <scoped_allocator>



The <scoped_allocator> in C++ provides a classes and utilities that allow advanced control over memory allocation, particularly dealing with nested or composed containers. It is used for handling memory allocation in cases where containers themselves contain other containers. It ensures that all objects within nested container share a common memory allocation.

The <scoped_allocator> consists of class named as scoped_allocator_adaptor. It allows for the forwarding the allocator arguments to multiple levels of containers, ensuring that both the outer container and nested containers can use the same allocator.

Including <scoped_allocator> Header

To include the <scoped_allocator> header in your C++ program, you can use the following syntax.

 #include <scoped_allocator> 

Functions of <scoped_allocator> Header

Below is list of all functions from <scoped_allocator> header.

Sr.No.Functions & Description
1allocate

It allocates uninitialized storage using the outer allocator.

2construct

It constructs an object in allocated storage.

3deallocate

It deallocates storage using the outer allocator.

4inner_allocator

It provides a access to the inner allocator used for allocating nested objects in a scoped allocator.

5max_size

It returns the largest allocation size supported by the outer allocator.

6outer_allocator

It is used to access the outermost allocator in a nested scoped_allocator_adaptor.

Creating a Scoped Allocator

In the following example, we are going to create a scoped_allocator_adaptor that adopts the standard allocator.

 #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; } 

Output

If we run the above code it will generate the following output −

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

Memory Management in Nested Containers

Consider the following example, where we are going to allocate and manage memory in the nested containers using std::scoped_allocator_adaptor.

 #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; } 

Output

Following is the output of the above code −

 0 0 0 0 1 2 0 2 4 
Advertisements
close