Namespaces
Variants

std::weak_ptr<T>:: ~weak_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)
~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> 의 public 멤버 함수)