名稱空間
變體
操作

std::return_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*)
(直到 C++20*)
return_temporary_buffer
(直到 C++20*)
顯式生命週期管理
 
定義於標頭檔案 <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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2072 C++98 std::get_temporary_buffer 分配的儲存
可能被多次解除分配
在這種情況下,行為是
未定義的

[編輯] 參閱

(在 C++17 中已棄用)(在 C++20 中已移除)
獲取未初始化儲存
(函式模板) [編輯]