Namespaces
Variants

std::pmr:: null_memory_resource

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
Definido en el encabezado <memory_resource>
std:: pmr :: memory_resource * null_memory_resource ( ) noexcept ;
(desde C++17)

Devuelve un puntero a un memory_resource que no realiza ninguna asignación.

Valor de retorno

Devuelve un puntero p a un objeto de duración de almacenamiento estático de un tipo derivado de std::pmr::memory_resource , con las siguientes propiedades:

  • su allocate() función siempre lanza std::bad_alloc ;
  • su deallocate() función no tiene efecto;
  • para cualquier memory_resource r , p - > is_equal ( r ) retorna & r == p .

El mismo valor se devuelve cada vez que se llama a esta función.

Ejemplo

El programa demuestra el uso principal de null_memory_resource : garantizar que un grupo de memoria que requiere memoria asignada en la pila NO asignará memoria en el montón si necesita más memoria.

#include <array>
#include <cstddef>
#include <iostream>
#include <memory_resource>
#include <string>
#include <unordered_map>
int main()
{
    // allocate memory on the stack
    std::array<std::byte, 20000> buf;
    // without fallback memory allocation on heap
    std::pmr::monotonic_buffer_resource pool{buf.data(), buf.size(),
                                             std::pmr::null_memory_resource()};
    // allocate too much memory
    std::pmr::unordered_map<long, std::pmr::string> coll{&pool};
    try
    {
        for (std::size_t i = 0; i < buf.size(); ++i)
        {
            coll.emplace(i, "just a string with number " + std::to_string(i));
            if (i && i % 50 == 0)
                std::clog << "size: " << i << "...\n";
        }
    }
    catch (const std::bad_alloc& e)
    {
        std::cerr << e.what() << '\n';
    }
    std::cout << "size: " << coll.size() << '\n';
}

Salida posible:

size: 50...
size: 100...
size: 150...
std::bad_alloc
size: 183