Shared pointer in C++

Level 4190 keystrokes

Two shared_ptr objects share ownership of one int; use_count shows the number of owners, which drops from 2 to 1 after reset.

C++ code

// make_shared allocates an int holding 42; sp1 is its first owner
1auto sp1 = make_shared<int>(42);
// Copying the pointer adds a second owner of the same int
2auto sp2 = sp1;
// Both point to the same value: prints 42 42
3cout << *sp1 << " " << *sp2 << endl;
// use_count is the number of owners: Count: 2
4cout << "Count: " << sp1.use_count() << endl;
// sp2 gives up ownership; the int stays alive because sp1 still owns it
5sp2.reset();
// Only one owner is left: Count: 1
6cout << "Count: " << sp1.use_count() << endl;

Output

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

  • <× 21
  • ;× 6
  • "× 6
  • (× 4
  • )× 4
  • _× 3
  • .× 3
  • :× 2
  • *× 2
  • =× 2

More C++ examples at level 4

← C++ typing practice