std::shared_ptr<T>::operator bool
声明
explicit operator bool() const noexcept;
检查 `*this` 是否存储了非 `null` 指针,即 `get() != nullptr`。
参数
(无)
返回值
如果 `*this` 存储了指针,则为 `true`,否则为 `false`。
备注
一个空的 `shared_ptr`(其中 `use_count() == 0`)可能存储了一个非 `null` 指针,该指针可通过 `get()` 访问,例如,如果它使用了别名构造函数创建。
示例
#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);
}
结果
ptr is not a valid pointer.
*ptr=7