std::shared_ptr<T>::operator bool

来自cppreference.com
 
 
内存管理库
分配器
内存资源
未初始化存储 (C++20 前*)
垃圾收集器支持 (C++23 前)
 
 
explicit operator bool() const noexcept;
(C++26 起为 constexpr)

检查 *this 是否存储非空指针。

返回值

get() != nullptr

注解

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 不是合法指针。\n";
}

int main()
{
    std::shared_ptr<int> ptr;
    report(ptr);
    
    ptr = std::make_shared<int>(7);
    report(ptr);
}

输出:

ptr 不是合法指针。
*ptr = 7

参阅

返回存储的指针
(公开成员函数) [编辑]