Namespaces
Variants
Views
Actions

std::weak_ptr<T>::~weak_ptr

From cppreference.com
< cpp‎ | memory‎ | weak ptr
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)

(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++23)
(C++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)
 
Dynamic memory management
Smart pointers
(C++11)
(C++11)
(C++11)
(until C++17)
(C++11)
(C++23)
Allocators
Memory resources
Uninitialized storage
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Garbage collection support
(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)
Miscellaneous
(C++20)
(C++11)
(C++11)
 
 
~weak_ptr();
(since C++11)

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

[edit] Example

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

#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
}

Output:

One link is a weak_ptr
Leaving...
  'A' reclaimed
  'B' reclaimed
  'C' reclaimed
All links are shared pointers
Leaving...

[edit] See also

destructs the owned object if no more shared_ptrs link to it
(public member function of std::shared_ptr<T>) [edit]