std::unique_ptr<T,Deleter>::operator bool

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

Allocators
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*)
Explicit lifetime management
 
 
explicit operator bool() const noexcept;
(since C++11)
(constexpr since C++23)

Checks whether *this owns an object, i.e. whether get() != nullptr.

Parameters

(none)

Return value

true if *this owns an object, false otherwise.

Example

#include <iostream>
#include <memory>
 
int main()
{
    std::unique_ptr<int> ptr(new int(42));
 
    if (ptr)
        std::cout << "before reset, ptr is: " << *ptr << '\n';
    ptr.reset();
    (ptr ? (std::cout << "after reset, ptr is: " << *ptr)
        : (std::cout << "after reset ptr is empty")) << '\n';
}

Output:

before reset, ptr is: 42
after reset ptr is empty

See also

returns a pointer to the managed object
(public member function)