std::weak_ptr::~weak_ptr(3)
π«Ά std::weak_ptr::~weak_ptr(3) β C++ Standard Libary manual π
okay bestie, gather round β this is the destructor page for std::weak_ptr, and it's from the C++ Standard Libary manual. It's short, it's sweet, and it's lowkey the βno dramaβ destructor. Let's get into it. β¨
π NAME π
std::weak_ptr::~weak_ptr β literally std::weak_ptr::~weak_ptr. That's the whole NAME line, bestie. Redundant? Maybe. Iconic? Absolutely. π
β¨ Synopsis β¨
~weak_ptr(); (since C++11)
So this destructor has been around since C++11. It destroys the weak_ptr object. Results in no effect to the managed object β like, the managed object gets zero effect from this. None. Nada. π«Ά
π Example π
The program shows the effect of "non-breaking" the cycle of std::shared_ptrs. (Yes, that's the exact phrase, and it's the whole point.) π¦
// 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; }
};
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...
π See also π
destructorβ destructs the owned object if no moreshared_ptrslink to it (public member function ofstd::shared_ptr<T>). π
source/version: http://cppreference.com, 2024.06.10 Β· page: std::weak_ptr::~weak_ptr(3) β byeee, go destroy your weak_ptr responsibly πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms