std::shared...operatorbool(3)

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

okay so bestie, welcome to the std::shared...operatorbool(3) page from the C++ Standard Libary manual πŸ’…βœ¨

✨ NAME ✨

std::shared_ptr::operatorbool β€” std::shared_ptr::operatorbool

This is the moment where we vibe-check a std::shared_ptr and ask: bestie, are you holding onto a pointer or not? πŸ‘‘

πŸ¦‹ Synopsis πŸ¦‹

explicit operator bool() const noexcept;

It checks if *this stores a non-null pointer, i.e. whether get() != nullptr. No cap, that's the whole job. πŸ’–

πŸŽ€ Parameters πŸŽ€

(none) β€” literally zero arguments, bestie. She takes no parameters. 🫢

🌸 Return value 🌸

true if *this stores a pointer, false otherwise. Simple as that, periodt. ✨

πŸ’œ Notes πŸ’œ

An empty shared_ptr (where use_count() == 0) may store a non-null pointer accessible by get(), e.g. if it were created using the aliasing constructor.

So yeah, an empty one can still have a pointer to show you through get() β€” that's the little plot twist, iykyk. πŸŒ€

πŸ”₯ Example πŸ”₯

// Run this code

#include <iostream>
#include <memory>

void report(std::shared_ptr<int> ptr)
{
    if (ptr)
        std::cout << "*ptr=" << *ptr << "\n";
    else
        std::cout << "ptr is not a valid pointer.\n";
}

int main()
{
    std::shared_ptr<int> ptr;
    report(ptr);

    ptr = std::make_shared<int>(7);
    report(ptr);
}

πŸ’– Output: πŸ’–

ptr is not a valid pointer.
*ptr=7

The first report hits the sad path, the second one slays with *ptr=7. πŸ”₯

🌈 See also 🌈

  • get β€” returns the stored pointer (public member function)

bye bestie β€” source/version shoutout to http://cppreference.com, date 2024.06.10, and it's the std::shared...operatorbool(3) page. πŸ’–πŸŽ€

πŸ“¦ where this page comes from