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 Created3 Resource() { cout << "Created" << endl; } // Destructor prints Destroyed4 ~Resource() { cout << "Destroyed" << endl; }5};6 // Start a block that limits the pointer's lifetime7{ // make_unique creates the Resource (prints Created) and ptr becomes its sole owner8 unique_ptr<Resource> ptr = make_unique<Resource>(); // Print Using resource while the object is still alive9 cout << "Using resource" << endl;// ptr goes out of scope here, deleting the Resource: prints Destroyed10}Output
Created Using resource Destroyed
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