std::shared_ptr<T>::operator bool

From cppreference.com
< cpp‎ | memory‎ | shared ptr
Memory management library
(exposition only*)
Uninitialized memory algorithms
(C++17)
(C++17)
(C++17)
(C++20)
Constrained uninitialized
memory algorithms
(C++20)
C Library

Allocators
(C++11)
(C++11)
Memory resources
Garbage collection support
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
Uninitialized storage
(until C++20*)
(until C++20*)
(until C++20*)
Explicit lifetime management
explicit operator bool ( ) const noexcept ;

Checks if *this stores a non-null pointer, i.e. whether get() != nullptr

Parameters

(none)

Return value

true if *this stores a pointer, false

Notes

An empty shared_ptr (where use_count() == 0) may store a non-null pointer accessible by get()

Example

#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

See also

returns the stored pointer
(public member function)