std::shared_ptr<T>::operator bool
来自 cppreference.cn
< cpp | 内存 | shared ptr
explicit operator bool() const noexcept; |
||
检查 *this 是否存储非空指针,即 get() != nullptr 是否为真。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
如果 *this 存储指针,则返回 true,否则返回 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
[编辑] 参阅
返回存储的指针 (public member function) |