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)
Definiert im Header <memory_resource>
std:: pmr :: memory_resource * null_memory_resource ( ) noexcept ;
(seit C++17)

Gibt einen Zeiger auf eine memory_resource zurück, die keine Allokation durchführt.

Rückgabewert

Gibt einen Zeiger p auf ein Objekt mit statischer Speicherdauer zurück, dessen Typ von std::pmr::memory_resource abgeleitet ist, mit den folgenden Eigenschaften:

  • seine allocate() Funktion wirft stets std::bad_alloc ;
  • seine deallocate() Funktion hat keine Wirkung;
  • für jedes memory_resource r , p - > is_equal ( r ) gibt & r == p zurück.

Derselbe Wert wird jedes Mal zurückgegeben, wenn diese Funktion aufgerufen wird.

Beispiel

Das Programm demonstriert die Hauptverwendung von null_memory_resource : sicherstellen, dass ein Speicherpool, der Speicher auf dem Stack benötigt, KEINEN Speicher auf dem Heap allokiert, falls mehr Speicher benötigt wird.

#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';
}

Mögliche Ausgabe:

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