std::weak_ptr::expired(3)

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

πŸ’– std::weak_ptr::expired(3) πŸ’–

Okay bestie, welcome to the C++ Standard Libary manual page for std::weak_ptr::expired β€” yes, that’s the manual name, typo and all, and we’re keeping it exactly as it is. This one is short, iconic, and lowkey important, so let’s get into it. πŸŽ€


✨ NAME ✨

std::weak_ptr::expired - std::weak_ptr::expired

It’s literally the std::weak_ptr::expired member function. Main character energy, no cap. πŸ’…


🌸 Synopsis 🌸

bool expired() const noexcept;  (since C++11)

Equivalent to use_count() == 0. The destructor for the managed object may not yet have been called, but this object's destruction is imminent (or may have already happened).

So yeah, it’s giving β€œis this thing already gone or about to be gone?” β€” and the noexcept is there, periodt. ✨


πŸ’… Parameters πŸ’…

Nope, nada, (none) β€” no parameters here, bestie. 🫢


πŸŽ€ Return value πŸŽ€

It returns true if the managed object has already been deleted, and false otherwise.

Simple. Clean. Iconic. πŸ¦‹


πŸ¦‹ Notes πŸ¦‹

⚠️ This function is inherently racy if the managed object is shared among threads. In particular, a false result may become stale before it can be used. A true result is reliable.

Bestie, read that again fr fr β€” the racy part is not a vibe. A false can go stale before you even use it, but a true result is reliable. Not me being dramatic, that’s just what the page says. 😭


🌈 Example 🌈

This example demonstrates how expired is used to check validity of the pointer.

The original says // Run this code, so here’s the code, exactly as it should be:

#include <iostream>
#include <memory>

std::weak_ptr<int> gw;

void f()
{
    if (!gw.expired())
        std::cout << "gw is valid\n";
    else
        std::cout << "gw is expired\n";
}

int main()
{
    {
        auto sp = std::make_shared<int>(42);
        gw = sp;

        f();
    }

    f();
}

⭐ Output ⭐

gw is valid
gw is expired

Ate. πŸ’…πŸ”₯


πŸ”₯ See also πŸ”₯

  • lock β€” creates a shared_ptr that manages the referenced object (public member function)
  • use_count β€” returns the number of shared_ptr objects that manage the object (public member function)

xoxo, your Unix bestie πŸ’– β€” sourced from http://cppreference.com, dated/versioned 2024.06.10, page std::weak_ptr::expired(3) 🫢✨

πŸ“¦ where this page comes from