Manual cleanup puts a burden on every path through a function. C++ can instead tie a resource to an ordinary object's lifetime. This approach is called RAII, short for Resource Acquisition Is Initialization: an object takes responsibility for a resource when it is initialized and releases that resource during destruction.
std::unique_ptr<T>, from <memory>, is an owning pointer for an object of type T. It represents sole ownership: two unique pointers cannot copy-own the same object. When a nonempty unique pointer is destroyed, it deletes the object it owns. Do not also call delete on that object yourself.
In C++14, std::make_unique<T>(arguments) creates a T using the supplied arguments and returns a unique pointer owning it. The angle brackets name the allocated type; the parentheses provide its construction values. For a pointed-to object, owner->member() calls a member just as (*owner).member() would. For an integer, *owner reads the integer.
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> visitors = std::make_unique<int>(16);
std::cout << *visitors << '\n';
}
The example prints 16. When visitors leaves scope, its destructor releases the integer; there is no separate delete statement to remember.
You may also see this declaration written as auto visitors = std::make_unique<int>(16);. Here auto asks the compiler to infer the variable's type from its initializer: it is still std::unique_ptr<int>, with the same ownership rules. It is not a different kind of pointer.
In the starter, reserved is declared without an initializer and therefore owns nothing yet. Add the initializer at that declaration. The supplied conditional prints -1 while it is empty and reads the integer only when an owner exists. An ordinary local integer would be simpler for this small calculation; the allocation is here to make ownership visible.
reserved using std::make_unique<int>(32). The guarded probe should print Reserved: 32; leave cleanup to the unique pointer.Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.