C++ memory_resource::new_object() Function



The C++ memory_resource::new_object() function is used to allocate memory for an object of a specified type using the associated memory resource.

This function simplifies memory management by allowing allocation to specific memory resources like monotonic or pool allocators. It constructs the object in-place, forwarding arguments to its constructor.

Syntax

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

new_object( CtorArgs&&... ctor_args );

Parameters

  • ctor_args − It indicates the arguments to forward to the constructor of U.

Return Value

This function returns a pointer to the allocated and constructed object.

The monotonic_buffer_resource does not have a new_object member function. Instead, we use the new operator with the monotonic_buffer_resource to allocate memory.

Example 1

Let's look at the following example, where we are going to create an integer object initialized to 12 using the memory pool.

#include <memory_resource>
#include <iostream>
int main() {
    char a[1123];
    std::pmr::monotonic_buffer_resource b(a, sizeof(a));
    std::pmr::polymorphic_allocator<int> x(&b);
    int* y = x.allocate(1);
    std::allocator_traits<std::pmr::polymorphic_allocator<int>>::construct(x, y, 12);
    std::cout << "Integer value: " << *y << std::endl;
    x.deallocate(y, 1);
    return 0;
}

Output

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

Integer value: 12
cpp_memory_resource.htm
Advertisements