std::weak_ptr<T>::use_count
來自 cppreference.com
long use_count() const noexcept; |
(C++11 起) | |
返回共享受管理物件所有權的 shared_ptr
例項數量,若受管理物件已被刪除,即 *this 為空,則返回 0。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
呼叫瞬間共享受管理物件所有權的 shared_ptr
例項數量。
[編輯] 注意
此函式的用法和行為與 std::shared_ptr::use_count 類似,但它返回不同的計數。
[編輯] 示例
執行此程式碼
#include <iostream> #include <memory> std::weak_ptr<int> gwp; void observe_gwp() { std::cout << "use_count(): " << gwp.use_count() << "\t id: "; if (auto sp = gwp.lock()) std::cout << *sp << '\n'; else std::cout << "??\n"; } void share_recursively(std::shared_ptr<int> sp, int depth) { observe_gwp(); // : 2 3 4 if (1 < depth) share_recursively(sp, depth - 1); observe_gwp(); // : 4 3 2 } int main() { observe_gwp(); { auto sp = std::make_shared<int>(42); gwp = sp; observe_gwp(); // : 1 share_recursively(sp, 3); // : 2 3 4 4 3 2 observe_gwp(); // : 1 } observe_gwp(); // : 0 }
輸出
use_count(): 0 id: ?? use_count(): 1 id: 42 use_count(): 2 id: 42 use_count(): 3 id: 42 use_count(): 4 id: 42 use_count(): 4 id: 42 use_count(): 3 id: 42 use_count(): 2 id: 42 use_count(): 1 id: 42 use_count(): 0 id: ??
[編輯] 參閱
檢查引用的物件是否已被刪除 (公開成員函式) |