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)
ヘッダーで定義 <memory_resource>
std:: pmr :: memory_resource * null_memory_resource ( ) noexcept ;
(C++17以降)

メモリ割り当てを一切行わない memory_resource へのポインタを返します。

戻り値

静的記憶域期間を持つオブジェクトへのポインタ p を返します。このオブジェクトの型は std::pmr::memory_resource から派生したものであり、以下の特性を持ちます:

  • その allocate() 関数は常に std::bad_alloc を送出する;
  • その deallocate() 関数は何の効果も持たない;
  • 任意の memory_resource r について、 p - > is_equal ( r ) & r == p を返す。

この関数が呼び出されるたびに同じ値が返されます。

このプログラムは null_memory_resource の主な使用法を示しています: スタック上に割り当てられたメモリを必要とするメモリプールが、より多くのメモリを必要とした場合にヒープ上にメモリを割り当てないことを保証します。

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

出力例:

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