Namespaces
Variants

std::shared_ptr<T>:: operator bool

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
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

参见

返回存储的指针
(公开成员函数)