std::return_temporary_buffer
来自 cppreference.cn
定义于头文件 <memory> |
||
template< class T > void return_temporary_buffer( T* p ); |
(在 C++17 中弃用) (在 C++20 中移除) |
|
释放由 p 引用的存储。
如果 p 不是先前调用 std::get_temporary_buffer 返回的指针值,或者已被中间的 std::return_temporary_buffer
调用而失效,则行为未定义。
目录 |
[编辑] 参数
p | - | 指向要释放的存储的指针 |
[编辑] 返回值
(无)
[编辑] 异常
不抛出异常。
[编辑] 示例
运行此代码
#include <algorithm> #include <iostream> #include <iterator> #include <memory> #include <string> int main() { const std::string s[] = {"string", "1", "test", "..."}; const auto p = std::get_temporary_buffer<std::string>(4); // requires that p.first is passed to return_temporary_buffer // (beware of early exit points and exceptions), or better use: std::unique_ptr<std::string, void(*)(std::string*)> on_exit(p.first, [](std::string* p) { std::cout << "returning temporary buffer...\n"; std::return_temporary_buffer(p); }); std::copy(s, s + p.second, std::raw_storage_iterator<std::string*, std::string>(p.first)); // has same effect as: std::uninitialized_copy(s, s + p.second, p.first); // requires that each string in p is individually destroyed // (beware of early exit points and exceptions) std::copy(p.first, p.first + p.second, std::ostream_iterator<std::string>{std::cout, "\n"}); std::for_each(p.first, p.first + p.second, [](std::string& e) { e.~basic_string<char>(); }); // same as: std::destroy(p.first, p.first + p.second); // manually reclaim memory if unique_ptr-like technique is not used: // std::return_temporary_buffer(p.first); }
输出
string 1 test ... returning temporary buffer...
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 2072 | C++98 | 由 std::get_temporary_buffer 分配的存储 可能被多次释放 |
在这种情况下,行为是 未定义的 |
[编辑] 参见
(在 C++17 中弃用)(在 C++20 中移除) |
获取未初始化的存储 (函数模板) |