Unique pointer in C++

Level 4205 keystrokes

A unique_ptr owns a Resource and deletes it automatically when it goes out of scope, so the messages appear in the order Created, Using resource, Destroyed.

C++ code

1class Resource {
2public:
// Constructor prints Created
3 Resource() { cout << "Created" << endl; }
// Destructor prints Destroyed
4 ~Resource() { cout << "Destroyed" << endl; }
5};
6
// Start a block that limits the pointer's lifetime
7{
// make_unique creates the Resource (prints Created) and ptr becomes its sole owner
8 unique_ptr<Resource> ptr = make_unique<Resource>();
// Print Using resource while the object is still alive
9 cout << "Using resource" << endl;
// ptr goes out of scope here, deleting the Resource: prints Destroyed
10}

Output

Created
Using resource
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.

  • <× 14
  • "× 6
  • ;× 5
  • {× 4
  • }× 4
  • (× 3
  • )× 3
  • _× 2
  • >× 2
  • :× 1

More C++ examples at level 4

← C++ typing practice