Namespaces
Variants

std::experimental:: make_unique_resource_checked

From cppreference.net
定义于头文件 <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 >>
make_unique_resource_checked ( R && r, const S & invalid, D && d )

noexcept ( /*见下文*/ ) ;
(库基础 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

异常

在存储资源句柄和删除器的初始化过程中抛出的任何异常。

注释

make_unique_resource_checked 的存在是为了避免使用无效参数调用删除器函数。

资源句柄 r 将被复制或移动到返回值中,所创建的 unique_resource 始终持有具有对象类型的底层资源句柄。

示例

#include <cstdio>
#include <experimental/scope>
int main()
{
    // 避免在fopen失败时调用fclose
    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.

参见