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 <<"' 已回收\n";}/*...*/void assign(std::weak_ptr<Node> p){ ptr = p;}void assign(std::shared_ptr<Node> p){ ptr = p;}}; enumclass 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<<"所有链接均为共享指针";}else{ C->assign(std::weak_ptr<Node>(A));std::cout<<"一个链接是 weak_ptr";}/*...*/std::cout<<"\n离开...\n";} int main(){ test_cyclic_graph(shared::some); test_cyclic_graph(shared::all);// 产生内存泄漏}
输出:
一个链接是 weak_ptr 离开... 'A' 已回收 'B' 已回收 'C' 已回收 所有链接均为共享指针 离开...
[编辑]参阅
如果没有更多 shared_ptr 指向所持有的对象,则析构该对象 ( std::shared_ptr<T> 的公开成员函数) |