std::shared_ptr::operator bool

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

参阅

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

版本历史

  • (当前 | 先前 2017年9月3日 (日) 21:59Fruderica讨论 | 贡献. . (1,055字节) (+103). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:57P12bot讨论 | 贡献 . . (952字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:06P12bot讨论 | 贡献 . . (952字节) (-25). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 14:53P12bot讨论 | 贡献 . . (977字节) (+345). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:40P12讨论 | 贡献 . . (632字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (632字节) (-39). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:55P12讨论 | 贡献 . . (671字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (671字节) (+671). . (Translated from the English version using Google Translate)