Weak Pointer in C++

Level 5480 keystrokes

In a doubly linked pair of nodes, next is a shared_ptr and prev is a weak_ptr, so there is no ownership cycle and both nodes are freed at the end. lock() turns the weak_ptr into a shared_ptr only while the object still exists.

C++ code

1class Node {
2public:
3 string name;
// next owns the following node
4 shared_ptr<Node> next;
// prev only observes; it does not increase the count, which avoids a cycle
5 weak_ptr<Node> prev;
6
// Print when a node is created and destroyed
7 Node(string n) : name(n) { cout << "Creating: " << name << endl; }
8 ~Node() { cout << "Destroying: " << name << endl; }
9};
10
// Prints "Creating: A" and "Creating: B"
11auto a = make_shared<Node>("A");
12auto b = make_shared<Node>("B");
13
// A owns B: B's count becomes 2
14a->next = b;
// B only points back to A weakly: A's count stays 1
15b->prev = a;
16
// Prints "A use count: 1"
17cout << "A use count: " << a.use_count() << endl;
// Prints "B use count: 2" (b and a->next)
18cout << "B use count: " << b.use_count() << endl;
19
// lock() returns a shared_ptr if A still exists, otherwise an empty one
20if (auto locked = b->prev.lock()) {
// Prints "B's prev: A"; at the end b is released first, then A is destroyed, which frees B
21 cout << "B's prev: " << locked->name << endl;
22}

Output

Creating: A
Creating: B
A use count: 1
B use count: 2
B's prev: A
Destroying: A
Destroying: B
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 34
  • "× 14
  • ;× 13
  • (× 9
  • )× 9
  • >× 8
  • :× 7
  • _× 6
  • =× 5
  • -× 4

More C++ examples at level 5

← C++ typing practice