Namespaces
Variants

std::shared_ptr<T>:: ~shared_ptr

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)
~shared_ptr ( ) ;

如果 * 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'); // 将输出 "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> 的公开成员函数)