std::pmr:: null_memory_resource
From cppreference.net
C++
Memory management library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<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 << "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