GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
std::weak_ptr::~weak_ptr(3) C++ Standard Libary std::weak_ptr::~weak_ptr(3)

std::weak_ptr::~weak_ptr - std::weak_ptr::~weak_ptr


~weak_ptr(); (since C++11)


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


The program shows the effect of "non-breaking" the cycle of std::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; }
};


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...


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

2022.07.31 http://cppreference.com

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.