CETL 0.0.0
 
Loading...
Searching...
No Matches
Example 6: Using the MemoryResourceDeleter class

Full example for cetl::pmr::MemoryResourceDeleter

#include <vector>
#include <algorithm>
#include <iostream>
#include <gtest/gtest.h>
TEST(example_06_memory_resource_deleter, example_usage)
{
// Let's say you wanted to store a bunch of buffers in a heap so you can get the largest one quickly.
// You could do something like this:
struct ByteBuffer
{
MemoryResourcePointer data;
};
cetl::pmr::memory_resource* resource = cetl::pmr::new_delete_resource();
auto buffer_0 = ByteBuffer{{resource->allocate(256), {resource, 256}}, 256};
auto buffer_1 = ByteBuffer{{resource->allocate(512), {resource, 512}}, 512};
auto buffer_2 = ByteBuffer{{resource->allocate(1024), {resource, 1024}}, 1024};
buffers.push_back(std::move(buffer_0));
buffers.push_back(std::move(buffer_1));
buffers.push_back(std::move(buffer_2));
std::make_heap(buffers.begin(), buffers.end(), [](const auto& lhs, const auto& rhs) {
return lhs.size < rhs.size;
});
auto& largest_buffer = buffers.front();
std::cout << "Largest buffer size: " << largest_buffer.size << std::endl;
// Now as long as the vector "buffers" is in scope, the buffers will be valid. When the vector is destroyed,
// the buffers will be freed using the correct memory resource.
}
T begin(T... args)
void * allocate(std::size_t size_bytes, std::size_t alignment=alignof(std::max_align_t))
Allocate memory.
Definition memory_resource.hpp:74
T end(T... args)
T endl(T... args)
T front(T... args)
T make_heap(T... args)
Extensions and utilities for types found in the standard memory header to better integrate with pmr t...
CETL polyfill header for C++17 types.
T push_back(T... args)