std::unique...get_deleter(3)

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

πŸŽ€ NAME πŸŽ€

okay so bestie, this is the std::unique...get_deleter(3) page from the C++ Standard Libary manual β€” yes, that's the manual name exactly, spelling and all. The actual name being documented? std::unique_ptr::get_deleter. Same energy, same page, periodt. πŸ’…

✨ Synopsis ✨

Deleter& get_deleter() noexcept;              (since C++11)
                                              (constexpr since C++23)
const Deleter& get_deleter() const noexcept;  (since C++11)
                                              (constexpr since C++23)

So you've got two overloads: the non-const one returns Deleter&, and the const one returns const Deleter&. Both are noexcept, both have been around since C++11, and both are constexpr since C++23. They hand you the deleter object that would be used for destruction of the managed object. That's the synopsis, slay. ✨

🫢 Parameters 🫢

(none) β€” nothing to pass, no arguments, zero notes. Just vibes. 🫢

πŸ’– Return value πŸ’–

The stored deleter object. That's the whole return-value tea. 🍡

🌈 Example 🌈

Here's the example, copied exactly because code does not need a glow-up:

// Run this code

#include <iostream>
#include <memory>

struct Foo
{
    Foo() { std::cout << "Foo() 0x" << std::hex << (void*)this << '\n'; }
    ~Foo() { std::cout << "~Foo() 0x" << std::hex << (void*)this << '\n'; }
};

struct D
{
    int number;

    void bar()
    {
        std::cout << "call D::bar(), my number is: " << std::dec << number << '\n';
    }

    void operator()(Foo* p) const
    {
        std::cout << "call deleter for Foo object 0x" << std::hex << (void*)p << '\n';
        delete p;
    }
};

int main()
{
    std::cout << "main start\n";

    std::unique_ptr<Foo, D> up1(new Foo(), D(42));
    D& del1 = up1.get_deleter();
    del1.bar();

    std::unique_ptr<Foo, D> up2(new Foo(), D(43));
    D& del2 = up2.get_deleter();
    auto* released = up2.release();
    del2(released);

    std::cout << "main end\n";
}

Output:

main start
Foo() 0x0x90cc30
call D::bar(), my number is: 42
Foo() 0x0x90cc50
call deleter for Foo object 0x0x90cc50
~Foo() 0x0x90cc50
main end
call deleter for Foo object 0x0x90cc30
~Foo() 0x0x90cc30

not me noticing the double 0x in the output β€” it's in the original, so it stays. πŸ’€

πŸ‘‘ See also πŸ‘‘

  • get_deleter returns the deleter of specified type, if owned (function template)

mwah πŸ’‹ β€” source/version/date: http://cppreference.com, 2024.06.10; footer title: std::unique...get_deleter(3). Go forth and get that deleter, bestie. 🌈✨

πŸ“¦ where this page comes from