std::shared_ptr::operator bool

From cppreference.com
< cpp‎ | memory‎ | shared ptr
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
 
 
explicit operator bool() const;

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

Contents

[edit] Parameters

(none)

[edit] Return value

true if *this stores a pointer, false otherwise.

[edit] Exceptions

noexcept specification:  
noexcept
  

[edit] 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.

[edit] Example

#include <iostream>
#include <memory>
 
typedef std::shared_ptr<int> IntPtr;
 
void report(IntPtr ptr) 
{
    if (ptr) {
        std::cout << "*ptr=" << *ptr << "\n";
    } else {
        std::cout << "ptr is not a valid pointer.\n";
    }
}
 
int main()
{
    IntPtr ptr;
    report(ptr);
 
    ptr = IntPtr(new int(7));
    report(ptr);
}

Output:

ptr is not a valid pointer.
*ptr=7

[edit] See also

returns the stored pointer
(public member function)