std::pmr::null_memory_resource
来自cppreference.com
在标头 <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(){// 栈上分配内存std::array<std::byte, 20000> buf; // 堆上进行无后备的内存分配std::pmr::monotonic_buffer_resource pool{buf.data(), buf.size(), std::pmr::null_memory_resource()}; // 分配过多内存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<<"大小: "<< i <<"...\n";}}catch(conststd::bad_alloc& e){std::cerr<< e.what()<<'\n';} std::cout<<"大小: "<< coll.size()<<'\n';}
可能的输出:
大小: 50... 大小: 100... 大小: 150... std::bad_alloc 大小: 183