std::out_ptr
來自 cppreference.com
定義於標頭檔案 <memory> |
||
template< class Pointer = void, class Smart, class... Args > auto out_ptr( Smart& s, Args&&... args ); |
(C++23 起) | |
返回一個帶有推導模板引數的 std::out_ptr_t,它透過引用捕獲重置引數。
如果返回值的構造(見下文)格式錯誤,則程式格式錯誤。
目錄 |
[編輯] 引數
s | - | 要適配的物件(通常是智慧指標) |
args... | - | 要捕獲的重置引數 |
[編輯] 返回值
std::out_ptr_t<Smart, P, Args&&>(s, std::forward<Args>(args)...),其中 P
是
-
Pointer
,如果Pointer
與 void 不同。否則, - Smart::pointer,如果它有效並表示一個型別。否則,
- Smart::element_type*,如果 Smart::element_type 有效並表示一個型別。否則,
- std::pointer_traits<Smart>::element_type*.
[編輯] 注意
使用者可以為模板引數 Pointer
指定模板引數,以便與接受 Pointer* 的外部函式進行互操作。
由於所有重置引數都是透過引用捕獲的,因此返回的 out_ptr_t
應該是一個臨時物件,並在包含對外部函式呼叫的完整表示式結束時銷燬,以避免懸空引用。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_out_ptr |
202106L |
(C++23) | std::out_ptr , std::inout_ptr |
202311L |
(C++26) | 獨立的 std::out_ptr 和 std::inout_ptr |
[編輯] 示例
使用 std::out_ptr
適配智慧指標以用於 sqlite3_open
,它需要一個 sqlite3**
作為輸出引數。
執行此程式碼
#include <memory> #include <sqlite3.h> int main() { auto close_db = [](sqlite3* db) { sqlite3_close(db); }; { // open an in-memory database, and manage its lifetime with std::unique_ptr std::unique_ptr<sqlite3, decltype(close_db)> up; sqlite3_open(":memory:", std::out_ptr(up)); sqlite3* db = up.get(); // do something with db ... } { // same as above, but use a std::shared_ptr std::shared_ptr<sqlite3> sp; sqlite3_open(":memory:", std::out_ptr(sp, close_db)); sqlite3* db = sp.get(); // do something with db ... } }
[編輯] 另請參閱
(C++23) |
建立一個帶有關聯智慧指標和重置引數的 inout_ptr_t (函式模板) |
(C++14)(C++20) |
建立一個管理新物件的唯一指標 (函式模板) |
(C++20 起) |
建立一個管理新物件的共享指標 (函式模板) |