std::get_temporary_buffer
来自 cppreference.cn
定义于头文件 <memory> |
||
template< class T > std::pair<T*, std::ptrdiff_t> |
(直到 C++11) | |
template< class T > std::pair<T*, std::ptrdiff_t> |
(自 C++11 起) (已弃用于 C++17) (已移除于 C++20) |
|
如果 count 为负数或零,则不执行任何操作。
否则,请求分配未初始化的连续存储,以容纳 count 个 T
类型的相邻对象。此请求不具约束力,实现可以改为分配用于任何其他数量(包括零)个 T
类型的相邻对象的存储。
是否支持过度对齐类型是实现定义的。 |
(自 C++11 起) |
目录 |
[编辑] 参数
count | - | 所需的对象数量 |
[编辑] 返回值
一个 std::pair,其成员 first
是指向已分配存储起始位置的指针,成员 second
是实际分配的存储中可容纳的对象数量。
如果 count <= 0 或分配的存储不足以存储单个 T
类型的元素,则结果的成员 first
是空指针,成员 second
为零。
[编辑] 注释
此 API 最初设计目的是提供比通用 operator new 更高效的实现,但没有创建这样的实现,并且此 API 已被弃用并移除。
[编辑] 示例
运行此代码
#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 425 | C++98 | 当 count <= 0 时的行为不明确 | 已明确 |
LWG 2072 | C++98 | 不允许分配不足的内存 | 允许 |
[编辑] 参见
(已弃用于 C++17)(已移除于 C++20) |
释放未初始化的存储 (函数模板) |
[静态] (C++23) |
通过分配器分配至少与请求大小一样大的存储空间 ( std::allocator_traits<Alloc> 的公共静态成员函数) |