std::unique_ptr::release(3)

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

πŸ’– NAME πŸ’–

okay bestie, welcome to std::unique_ptr::release(3) from the C++ Standard Libary manual πŸ’… (yes, that’s the manual name, no cap). The name is literally:

std::unique_ptr::release β€” std::unique_ptr::release

like, that’s it. it’s giving β€œthe function is the name, the name is the function” energy πŸ’€βœ¨

πŸ¦‹ Synopsis πŸ¦‹

pointer release() noexcept;  (since C++11)
                             (constexpr since C++23)

okay so what does it do? It releases the ownership of the managed object, if any. 🫢

After the call, get() returns nullptr. periodt.

⚠️ bestie, the caller is responsible for cleaning up the object (e.g. by use of get_deleter()). that’s on you, not the unique_ptr. πŸ’…

🌸 Parameters 🌸

(none) β€” literally zero parameters, not a single one, we love a no-arg icon πŸ‘‘

✨ Return value ✨

A pointer to the managed object, or nullptr if there was no managed object β€” i.e. the value which would be returned by get() before the call. iykyk πŸ’–

πŸŽ€ Example πŸŽ€

here’s the example, bestie β€” run this code:

// Run this code

#include <cassert>
#include <iostream>
#include <memory>

struct Foo
{
    Foo() { std::cout << "Foo\n"; }
    ~Foo() { std::cout << "~Foo\n"; }
};

// Ownership of the Foo resource is transferred when calling this function
void legacy_api(Foo* owning_foo)
{
    std::cout << __func__ << '\n';
    // [legacy code that no one understands or dares touch anymore]
    // [...]
    delete owning_foo;
}

int main()
{
    std::unique_ptr<Foo> managed_foo(new Foo);
    // [code that might return or throw or some such]
    // [...]
    legacy_api(managed_foo.release());

    assert(managed_foo == nullptr);
}

🌈 Output 🌈

Foo
legacy_api
~Foo

πŸ‘‘ See also πŸ‘‘

  • get β€” returns a pointer to the managed object (public member function)
  • get_deleter β€” returns the deleter that is used for destruction of the managed object (public member function)
  • reset β€” replaces the managed object (public member function)

and that’s the whole vibe check, bestie πŸ’– source/version: http://cppreference.com Β· date: 2024.06.10 Β· title: std::unique_ptr::release(3) 🫢✨

πŸ“¦ where this page comes from