C++ Library -



The 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 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 Header

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

#include 

Functions of Header

Below is list of all functions from header.

Sr.No. Functions & Description
1 allocate

It allocates uninitialized storage using the outer allocator.

2 construct

It constructs an object in allocated storage.

3 deallocate

It deallocates storage using the outer allocator.

4 inner_allocator

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

5 max_size

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

6 outer_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 
#include 
#include 
#include 
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 
#include 
#include 
#include 
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