std::experimental::make_unique_resource_checked
来自 cppreference.cn
< 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>> |
(library fundamentals TS v3) | |
创建 unique_resource
,使用 std::forward<R>(r) 初始化其存储的资源句柄,并使用 std::forward<D>(d) 初始化其删除器。当且仅当 bool(r == invalid) 为 false 时,创建的 unique_resource
拥有资源。
如果表达式 r == invalid 无法语境转换 (contextually converted) 为 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.