std::weak_ptr<T>::~weak_ptr
来自 cppreference.com
~weak_ptr(); |
(自 C++11 起) | |
销毁 weak_ptr
对象。对托管对象没有任何影响。
[编辑] 示例
该程序展示了“不破坏” std::shared_ptr 循环的效果。
运行此代码
#include <iostream> #include <memory> #include <variant> class Node { char id; std::variant<std::weak_ptr<Node>, std::shared_ptr<Node>> ptr; public: Node(char id) : id{id} {} ~Node() { std::cout << " '" << id << "' reclaimed\n"; } /*...*/ void assign(std::weak_ptr<Node> p) { ptr = p; } void assign(std::shared_ptr<Node> p) { ptr = p; } }; enum class shared { all, some }; void test_cyclic_graph(const shared x) { auto A = std::make_shared<Node>('A'); auto B = std::make_shared<Node>('B'); auto C = std::make_shared<Node>('C'); A->assign(B); B->assign(C); if (shared::all == x) { C->assign(A); std::cout << "All links are shared pointers"; } else { C->assign(std::weak_ptr<Node>(A)); std::cout << "One link is a weak_ptr"; } /*...*/ std::cout << "\nLeaving...\n"; } int main() { test_cyclic_graph(shared::some); test_cyclic_graph(shared::all); // produces a memory leak }
输出
One link is a weak_ptr Leaving... 'A' reclaimed 'B' reclaimed 'C' reclaimed All links are shared pointers Leaving...
[编辑] 另请参见
如果不再有 shared_ptr 指向它,则析构拥有对象( std::shared_ptr<T> 的公共成员函数) |