std::shared_ptr<T>::operator bool
来自 cppreference.cn
< cpp | memory | shared ptr
explicit operator bool() const noexcept; |
||
检查 *this 是否存储非空指针,即 get() != nullptr 是否为真。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
true 如果 *this 存储指针,否则为 false 。
[编辑] 注解
空的 shared_ptr (其中 use_count() == 0) 可能存储可通过 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
[编辑] 参见
返回存储的指针 (公共成员函数) |