std::shared_ptr::operator bool

1
explicit operator bool() const;

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

Parameters

(none).

Return value

true if *this stores a pointer, false otherwise.

Exceptions

noexcept specification:
noexcept

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.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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:

1
2
ptr is not a valid pointer.
*ptr=7

See also

returns a pointer to the managed object
(public member function)
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.