std::unique_ptr<T,Deleter>>::operator bool
自 C++11 起
explicit operator bool() const noexcept;
自 C++23 起
constexpr explicit operator bool() const noexcept;
检查*this
是否拥有一个对象,即get() != nullptr
。
参数
(无)
返回值
如果*this
拥有一个对象,则为true
,否则为false
。
示例
#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';
}
结果
before reset, ptr is: 42
after reset ptr is empty