Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::weak_ptr<T>::~weak_ptr

      From cppreference.com
      <cpp‎ |memory‎ |weak ptr
       
       
      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*)
      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)
       
       
      ~weak_ptr();
      (since C++11)

      Destroys theweak_ptr object. Results in no effect to the managed object.

      [edit]Example

      The program shows the effect of "non-breaking" the cycle ofstd::shared_ptrs.

      Run this code
      #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;}}; 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<<"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}

      Output:

      One link is a weak_ptrLeaving...  'A' reclaimed  'B' reclaimed  'C' reclaimedAll links are shared pointersLeaving...

      [edit]See also

      destructs the owned object if no moreshared_ptrs link to it
      (public member function ofstd::shared_ptr<T>)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/memory/weak_ptr/%7Eweak_ptr&oldid=153996"

      [8]ページ先頭

      ©2009-2025 Movatter.jp