Destructor Order
Completed
Write class Tracer that prints +NAME when constructed and -NAME when destroyed. Read names and create one Tracer per name as local variables in nested blocks: the first name's object lives in the outermost block, the next in a block inside it, and so on (use recursion). Print end after everything is destroyed.
Input
n, then n names.
Output
The construction/destruction trace, then end.
Example
Input
3 A B C
Output
+A +B +C -C -B -A end
Editor
C++
Hints
Local objects are destroyed in reverse order of creation, when their scope ends.
Solution explanation
Deterministic destruction is what makes RAII reliable in C++.
Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Tracer {
public:
explicit Tracer(string name) : name_(name) { cout << "+" << name_ << "\n"; }
~Tracer() { cout << "-" << name_ << "\n"; }
private:
string name_;
};
void nest(const vector<string> &names, size_t i) {
if (i == names.size()) return;
Tracer t(names[i]);
nest(names, i + 1);
}
int main() {
int n;
cin >> n;
vector<string> names(n);
for (auto &s : names) cin >> s;
nest(names, 0);
cout << "end\n";
return 0;
}