Skip to main content

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

Since C++11
explicit operator bool() const noexcept;
Since C++23
constexpr explicit operator bool() const noexcept;

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';
}
Result
before reset, ptr is: 42
after reset ptr is empty

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

Since C++11
explicit operator bool() const noexcept;
Since C++23
constexpr explicit operator bool() const noexcept;

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';
}
Result
before reset, ptr is: 42
after reset ptr is empty