Smart Pointer in C++
Level 5262 keystrokes
Creates a Resource with make_unique and holds it in a unique_ptr. When ptr goes out of scope, the object is deleted automatically and its destructor prints "Data destroyed".
C++ code
// Resource prints a message when it is created and when it is destroyed1class Resource {2public: // Name used in the messages3 string name; // Constructor: the initializer list sets name, then "created" is printed4 Resource(string n) : name(n) {5 cout << name << " created" << endl;6 } // Destructor: runs automatically when the object is destroyed7 ~Resource() {8 cout << name << " destroyed" << endl;9 }10};11 // make_unique creates the object on the heap and prints "Data created"// ptr is the sole owner; leaving the scope deletes the object ("Data destroyed")12unique_ptr<Resource> ptr = make_unique<Resource>("Data");// -> accesses a member through the pointer: prints "Using: Data"13cout << "Using: " << ptr->name << endl;Output
Data created Using: Data Data 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.
<× 20"× 8;× 6(× 4)× 4:× 3{× 3}× 3>× 3_× 2