名稱空間
變體
操作

std::get_temporary_buffer

來自 cppreference.com
< cpp‎ | 記憶體
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
get_temporary_buffer
(直到 C++20*)
顯式生命週期管理
 
定義於標頭檔案 <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 型別相鄰物件分配儲存空間。

是否支援過度對齊型別是實現定義的。

(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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 425 C++98 count <= 0 時的行為不明確 已明確
LWG 2072 C++98 不允許分配不足的記憶體 允許

[編輯] 另請參閱

(在 C++17 中已棄用)(在 C++20 中已移除)
釋放未初始化儲存
(函式模板) [編輯]
[static] (C++23)
透過分配器分配至少請求大小的儲存空間
(std::allocator_traits<Alloc> 的公共靜態成員函式) [編輯]