We are looking into the idiom:

if (auto spt = wp.lock()) {
    spt->hello();
}

๐Ÿ” Whatโ€™s Happening?


โœ… Why if (auto spt = wp.lock()) works:

C++ allows you to use a shared_ptr in a boolean context โ€” it implicitly checks:

if (spt) // is equivalent to: if (spt.get() != nullptr)

So, this is shorthand for:

auto spt = wp.lock();
if (spt != nullptr) {
    spt->hello();
}

But C++ lets you write it concisely:

if (auto spt = wp.lock()) {
    spt->hello();
}

๐Ÿง  Summary:

Expression Meaning
if (auto spt = wp.lock()) If object still exists, proceed
if (spt) Checks if spt is non-null
shared_ptr in boolean context True if it holds a non-null pointer