GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — C++ Library - <memory_resource>
Selected Reading
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> HeaderTo include the <memory_resource> header in your C++ program, you can use the following syntax. #include <memory_resource> Functions of <memory_resource> HeaderBelow is list of all functions from <memory_resource> header.
Custom Memory ResourceIn 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;
}
OutputOutput of the above code is as follows − Result : 11 Using synchronized_pool_resourceConsider 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;
}
OutputFollowing is the output of the above code − 1 2 3 4 Advertisements
| ||||||||||||||||||||
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |