std::shared_ptr<T>::~shared_ptr
來自 cppreference.com
< cpp | 記憶體 | shared ptr
~shared_ptr(); |
||
若 *this 擁有一個物件且 *this 是最後一個擁有該物件的 shared_ptr
,則透過其所擁有的刪除器銷燬該物件。
銷燬之後,曾與 *this 共享所有權的智慧指標(若存在)將報告其 use_count() 比先前的值少一。
[編輯] 註解
不同於 std::unique_ptr,即使被管理指標為空,std::shared_ptr 的刪除器仍然會被呼叫。
[編輯] 示例
執行此程式碼
#include <iostream> #include <memory> struct S { S() { std::cout << "S::S()\n"; } ~S() { std::cout << "S::~S()\n"; } struct Deleter { void operator()(S* s) const { std::cout << "S::Deleter()\n"; delete s; } }; }; int main() { auto sp = std::shared_ptr<S>{new S, S::Deleter{}}; auto use_count = [&sp](char c) { std::cout << c << ") use_count(): " << sp.use_count() << '\n'; }; use_count('A'); { auto sp2 = sp; use_count('B'); { auto sp3 = sp; use_count('C'); } use_count('D'); } use_count('E'); // sp.reset(); // use_count('F'); // would print "F) use_count(): 0" }
輸出
S::S() A) use_count(): 1 B) use_count(): 2 C) use_count(): 3 D) use_count(): 2 E) use_count(): 1 S::Deleter() S::~S()
[編輯] 參閱
銷燬 weak_ptr ( std::weak_ptr<T> 的公開成員函式) |