Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

C++ memory_resource::release() function



The C++, memory_resource::release() function is used to release memory allocated by a custom memory resources back to the system or reset the internal memory pools for reuse.

This function is typically overridden in user-defined memory resource to implement custom memory management strategies. When it is invoked, it ensures efficient memory reuse without repeated allocations.

Syntax

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

void.release();

Parameters

It does not accepts any parameter.

Return Value

It returns a raw pointer to the managed object.

Example 1

Let's look at the following example, where we are going to consider the basic usage of the release() function.

#include <iostream>
#include <memory_resource>
#include <vector>
int main() {
    std::pmr::monotonic_buffer_resource a;
    int* x = static_cast<int*>(a.allocate(3 * sizeof(int)));
    for (int i = 0; i < 3; ++i) {
        x[i] = i * 10;
    }
    for (int i = 0; i < 3; ++i) {
        std::cout << x[i] << " ";
    }
    std::cout << std::endl;
    a.release();
    return 0;
}

Output

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

0 10 20 

Example 2

Consider the following example, where the unsynchronized_pool_resource allocates the memory for use in a single-threaded context after invoking the release() all the memory allocated from this resource is returned to the system.

#include <iostream>
#include <memory_resource>
int main() {
    std::pmr::unsynchronized_pool_resource a;
    void* x1 = a.allocate(11);
    void* x2 = a.allocate(12);
    std::cout << "Memory allocated.\n";
    a.release();
    std::cout << "Memory released.\n";
    return 0;
}

Output

Output of the above code is as follows −

Memory allocated.
Memory released.
cpp_memory_resource.htm
Advertisements