Namespaces
Variants

std:: get_temporary_buffer

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* )
get_temporary_buffer
( 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>
template < class T >

std:: pair < T * , std:: ptrdiff_t >

get_temporary_buffer ( std:: ptrdiff_t count ) ;
(C++11 前)
template < class T >

std:: pair < T * , std:: ptrdiff_t >

get_temporary_buffer ( std:: ptrdiff_t count ) noexcept ;
(C++11 起)
(C++17 中弃用)
(C++20 中移除)

如果 count 为负数或零,则不执行任何操作。

否则,请求为 count 个相邻的 T 类型对象分配未初始化的连续存储空间。该请求不具约束力,实现可以选择为任意数量(包括零个)相邻的 T 类型对象分配存储空间。

是否支持 超对齐 类型由实现定义。

(since 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);
    // 要求必须将 p.first 传递给 return_temporary_buffer
    // (注意提前退出点和异常情况),更推荐使用:
    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));
    // 效果等同于:std::uninitialized_copy(s, s + p.second, p.first);
    // 要求单独销毁 p 中的每个字符串
    // (注意提前退出点和异常情况)
    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>();
    }); // 等同于:std::destroy(p.first, p.first + p.second);
    // 如果未使用 unique_ptr 类似技术,需手动回收内存:
    // std::return_temporary_buffer(p.first);
}

输出:

string
1
test
...
returning temporary buffer...

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 425 C++98 count <= 0 时的行为不明确 已明确说明
LWG 2072 C++98 不允许分配不足的内存 允许分配

参见

(C++17 中弃用) (C++20 中移除)
释放未初始化的存储空间
(函数模板)
[static] (C++23)
通过分配器分配至少达到请求大小的存储空间
( std::allocator_traits<Alloc> 的公开静态成员函数)