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 을 throw합니다;
  • 해당 할당자의 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