名稱空間
變體
操作

std::shared_ptr<T>::operator bool

來自 cppreference.com
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
 
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) [編輯]