C++ Library - <memory_resource>



The <memory_resource> header in C++17 introduces a set of classes and functions to support the polymorphic memory resources. It introduces a flexible way to allocate and deallocate memory by abstracting the memory management mechanism into customizable memory resource class.

The ability of <memory_resource> is that it decouples the memory allocation logic from containers an algorithms, enabling control over memory management. The core of this library is std::pmr::memory_resource class, which defines an abstract interface for memory allocation. These memory resources can be then used with containers that support polymorphic allocators, such as std::pmr::vector, std::pmr::string and other.

Including <memory_resource> Header

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

#include <memory_resource>

Functions of <memory_resource> Header

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

Sr.No. Functions & Description
1 allocate

It allocates the memory.

2 deallocate

It deallocates the memory.

3 construct

It constructs an object in allocated storage.

4 release

It release all allocated memory.

5 options

It returns the options that control the pooling behaviour of this resource.

6 upstream_resource

It returns a pointer to the upstream memory resource.

7 new_object

It allocates and constructs an object.

8 delete_object

It destroys and deallocates an object.

9 resource

It returns a pointer to the underlying memory resource.

Custom Memory Resource

In the following example, we are going to define a custom memory resource by inheriting from std::pmr::memory_resource.

#include <iostream>
#include <memory_resource>
class x: public std::pmr::memory_resource {
   protected: void * do_allocate(size_t size, size_t alignment) override {
      return::operator new(size);
   }
   void do_deallocate(void * p, size_t, size_t) override {
      ::operator delete(p);
   }
   bool do_is_equal(const memory_resource & other) const noexcept override {
      return this == & other;
   }
};
int main() {
   x myResource;
   int * a = static_cast < int * > (myResource.allocate(sizeof(int)));
   * a = 11;
   std::cout << "Result : " << * a << std::endl;
   myResource.deallocate(a, sizeof(int));
   return 0;
}

Output

Output of the above code is as follows −

Result : 11

Using synchronized_pool_resource

Consider the following example, where we are going to use the synchronized_pool_resource.

#include <iostream>
#include <memory_resource>
int main() {
   std::pmr::synchronized_pool_resource x;
   int * arr = static_cast < int * > (x.allocate(sizeof(int) * 4));
   for (int a = 0; a < 4; ++a) {
      arr[a] = a + 1;
      std::cout << arr[a] << " ";
   }
   std::cout << std::endl;
   x.deallocate(arr, sizeof(int) * 4);
   return 0;
}

Output

Following is the output of the above code −

1 2 3 4
Advertisements