std::experi...urce_checked(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

okay bestie, this one's from the C++ Standard Libary manual β€” yes, that's literally the manual name, typo and all, no cap πŸ™ˆ β€” and it's page 3. We're about to make a unique_resource that knows when not to call its deleter. Main character energy fr fr πŸ’…

πŸ’– NAME πŸ’–

  • std::experimental::make_unique_resource_checked β€” the original repeats the same name after the dash, so here it is again: std::experimental::make_unique_resource_checked. Iconic, honestly ✨

✨ Synopsis ✨

Defined in header <experimental/scope>.

This is the library fundamentals TS v3 version, iykyk πŸ¦‹

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(/*see below*/);

So what's the tea? It creates a unique_resource, initializes its stored resource handle with std::forward<R>(r), and initializes its deleter with std::forward<D>(d). The created unique_resource owns the resource if and only if bool(r == invalid) is false.

The program is ill-formed if the expression r == invalid cannot be contextually converted to bool, and the behavior is undefined if the conversion results in undefined behavior or throws an exception. That's the serious part, bestie β€” do not ignore it 😭

😭 Exceptions 😭

Any exception thrown in initialization of the stored resource handle and the deleter.

noexcept specification:

noexcept(

    std::is_nothrow_constructible_v<std::decay_t<R>, R> &&
    std::is_nothrow_constructible_v<std::decay_t<D>, D>

)

🧠 Notes 🧠

make_unique_resource_checked exists to avoid calling a deleter function with an invalid argument. Periodt.

Resource handle r is either copied or moved into the return value, and the created unique_resource always holds an underlying resource handle with object type. Slay 🌸

🌈 Example 🌈

// Run this code

#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 exits.");
    else
        std::puts("The file does not exist.");
}

πŸ“ Possible output πŸ“

The file does not exist.

πŸ‘€ See also πŸ‘€

  • Category:
    • conditionally noexcept

πŸ¦‹ cute little sign-off: the source/version is http://cppreference.com, dated 2024.06.10. That's the footer tea, bestie. Mwah πŸ’‹βœ¨
πŸ“¦ where this page comes from