C++ memory_resource::delete_object() Function



The C++ memory_resource::delete_object() function is used to delete objects allocated by a custom memory resource. This function calls the destructor of the specified object and deallocates the memory using the memory resource that initially allocated it.

It ensures proper cleanup of objects while following to the memory resource allocation and deallocation rules.

Syntax

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

void delete_object( U* p );

Parameters

  • p − It indicates the pointer to the object to destroy and deallocate.

Return Value

It does not return any value.

The memory_resource class does not provide member functions like new_object and delete_object, To correctly use memory_resource or monotonic_buffer_resource, you should use the allocate() and deallocate() functions for memory management.

Example 1

Let's look at the following example, where we are going to consider the basic usage with the polymorphic memory resource.

#include <memory_resource>
#include <iostream>
#include <new>
struct a {
    int x;
    a(int val) : x(val) {
        std::cout << "Object constructed with value: " << x << "\n";
    }
    ~a() {
        std::cout << "Object destroyed\n";
    }
};
int main() {
    char buffer[1112];
    std::pmr::monotonic_buffer_resource y(buffer, sizeof(buffer));
    void* raw_memory = y.allocate(sizeof(a), alignof(a));
    a* obj = new (raw_memory) a(12);
    obj->~a();
    y.deallocate(raw_memory, sizeof(a), alignof(a));
    return 0;
}

Output

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

Object constructed with value: 12
Object destroyed
cpp_memory_resource.htm
Advertisements