std::experimental::make_unique_resource_checked
來自 cppreference.com
< cpp | experimental | unique_resource
定義於標頭檔案 <experimental/scope> |
||
template< class R, class D, class S = std::decay_t<R> > std::experimental::unique_resource<std::decay_t<R>, std::decay_t<D>> |
(庫基礎 TS v3) | |
建立一個 unique_resource
,將其儲存的資源控制代碼用 std::forward<R>(r) 初始化,其刪除器用 std::forward<D>(d) 初始化。當且僅當 bool(r == invalid) 為 false 時,建立的 unique_resource
擁有該資源。
如果表示式 r == invalid 無法上下文轉換為 bool,則程式格式錯誤;如果轉換導致未定義行為或丟擲異常,則行為未定義。
目錄 |
[編輯] 引數
r | - | 資源控制代碼 |
d | - | 用於處置資源的刪除器 |
invalid | - | 指示資源控制代碼無效的值 |
[編輯] 返回值
一個如上所述的 unique_resource
。
[編輯] 異常
在初始化儲存的資源控制代碼和刪除器時丟擲的任何異常。
noexcept 規範:
noexcept(
std::is_nothrow_constructible_v<std::decay_t<R>, R> &&
std::is_nothrow_constructible_v<std::decay_t<D>, D>
[編輯] 注意
make_unique_resource_checked
的存在是為了避免使用無效引數呼叫刪除器函式。
資源控制代碼 r 被複制或移動到返回值中,並且建立的 unique_resource
始終持有一個底層資源控制代碼,其型別為物件型別。
[編輯] 示例
執行此程式碼
#include <cstdio> #include <experimental/scope> int main() { // avoid calling fclose when fopen fails auto file = std::experimental::make_unique_resource_checked( std::fopen("potentially_nonexistent_file.txt", "r"), nullptr, [](std::FILE *fptr) { std::fclose(fptr); } ); if (file.get()) std::puts("The file exists."); else std::puts("The file does not exist."); }
可能的輸出
The file does not exist.