Shared Pointer in C++

Level 5329 keystrokes

Two shared_ptr objects share ownership of one Node. use_count() goes from 1 to 2 when p1 is copied to p2, and the Node is destroyed only when the last owner goes away.

C++ code

// Node prints a message when it is created and destroyed
1class Node {
2public:
3 int value;
// Constructor: prints "Node 42 created"
4 Node(int v) : value(v) { cout << "Node " << v << " created" << endl; }
// Destructor: runs when the last shared_ptr releases the object
5 ~Node() { cout << "Node " << value << " destroyed" << endl; }
6};
7
// make_shared allocates the Node and its reference count together
8shared_ptr<Node> p1 = make_shared<Node>(42);
// Only p1 owns it: prints "Count: 1"
9cout << "Count: " << p1.use_count() << endl;
// Copying the shared_ptr adds an owner (count + 1)
10shared_ptr<Node> p2 = p1;
// Prints "Count: 2"; when both go out of scope, "Node 42 destroyed" is printed
11cout << "Count: " << p1.use_count() << endl;

Output

Node 42 created
Count: 1
Count: 2
Node 42 destroyed
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.

  • <× 31
  • "× 12
  • ;× 8
  • (× 6
  • )× 6
  • _× 5
  • :× 4
  • {× 3
  • }× 3
  • >× 3

More C++ examples at level 5

← C++ typing practice