C++ memory_resource::options() Function



The C++ memory_resource::options() function is a structure inside the std::pmr::unsynchronized_pool_resource class, that provides configuration options that controls the behaviour of the resource.

This it has include the settings related to how memory blocks are allocated and how large or short block should be.

Exception: The options structure, we can only use with std::pmr::unsynchronized_pool_resource class.

Syntax

Following is the syntax for std::memory_resource::options() function.

std::pmr::pool_options options() const;  

Parameters

It does not accept any parameters.

Return Value

This function returns the options that controls the pooling behaviour of this resource.

Example 1

In this example we will demonstrate use of std::pmr::unsynchronized_pool_resource without setting any custom options. so the default options will be used.

In the below example we are not setting any custom options, so the default options may be used by the resource. First, we have created a polymorphic allocator and then allocated memory for 5 integers using the allocator. Then we have assigned values to each element of the array and then printed the values of the array. After that, we have deallocated the memory using the deallocate() function.

#include <iostream>
#include <memory>
#include <vector>
#include <memory_resource>

using namespace std;

int main () {

    std::pmr::unsynchronized_pool_resource resource;
    std::pmr::polymorphic_allocator<int> allocator(&resource);

    int *p = allocator.allocate(5);
    for(int i = 0; i < 5; i++) {
        p[i] = i;
    }

    for(int i = 0; i < 5; i++) {
        cout << p[i] << endl;
    }

    allocator.deallocate(p, 5);
    return 0;
}

Output

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

0
1
2
3
4

Example 2

Now we will see the example where Custom max_block_size and initial_pool_size are set.

In this code, we are setting the custom options for the resource. First, we have created a polymorphic allocator and then allocated memory for 5 integers using the allocator. Then we have assigned values to each element of the array and then printed the values of the array. After that, we have deallocated the memory using the deallocate() function.

#include <iostream>
#include <memory>
#include <vector>
#include <memory_resource>

using namespace std;

int main () {
  
   std::pmr::pool_options opts;
   opts.max_blocks_per_chunk = 10;
   opts.largest_required_pool_block = 1024;
   std::pmr::unsynchronized_pool_resource resource(opts);
   std::pmr::polymorphic_allocator<int> allocator(&resource);
   
   int *p = allocator.allocate(5);
    for(int i = 0; i < 5; i++) {
        p[i] = i;
    }

    for(int i = 0; i < 5; i++) {
        cout << p[i] << endl;
    }

    allocator.deallocate(p, 5);
    return 0;
}

Output

Following is the output of the above code −

0
1
2
3
4
cpp_memory_resource.htm
Advertisements