unique_ptr
Completed
Create a class Resource that prints acquire NAME in its constructor and release NAME in its destructor. For each input name, create it with make_unique inside a block, print using NAME, and let the block end.
Input
n, then n names.
Output
The event trace.
Example
Input
2 file socket
Output
acquire file using file release file acquire socket using socket release socket
Editor
C++
Hints
A unique_ptr deletes its object automatically when it goes out of scope.
Solution explanation
This is RAII: tie a resource's lifetime to an object so cleanup can't be forgotten.
Show solution
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Resource {
public:
explicit Resource(string name) : name_(name) { cout << "acquire " << name_ << "\n"; }
~Resource() { cout << "release " << name_ << "\n"; }
const string &name() const { return name_; }
private:
string name_;
};
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string name;
cin >> name;
{
auto r = make_unique<Resource>(name);
cout << "using " << r->name() << "\n";
}
}
return 0;
}