Namespaces
Variants
Views
Actions

std::shared_ptr<T>::operator bool

From cppreference.com
< cpp‎ | memory‎ | shared ptr
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)
Stacktrace
 
Dynamic memory management
Smart pointers
(C++11)
(C++11)
(C++11)
(until C++17)
(C++11)
Allocators
Memory resources
Uninitialized storage
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Garbage collection support
Miscellaneous
(C++20)
(C++11)
(C++11)
C Library
Low level memory management
 
 
explicit operator bool() const noexcept;

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] 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>
 
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

[edit] See also

returns the stored pointer
(public member function) [edit]