C++: Objects that clean up

Watch a destructor run at the end of a scope.

What to build

A class whose destructor runs automatically.

Requirements

  • Write a class Guard whose constructor takes a name and prints open NAME, and whose destructor prints close NAME.
  • Do not change main.

Input

Three words.

Output

Six lines plus end, in the order the program produces them.

Constraints

Each word has at most 20 letters.

Example

Input:

a b c

Output:

open a
open b
open c
close c
close b
end
close a

Why it works

C++ guarantees that a destructor runs when its object leaves scope, in reverse order of creation, so cleanup needs no extra code.

Examples

Example 1 · Input
a b c
Expected output
open a
open b
open c
close c
close b
end
close a
Example 2 · Input
x y z
Expected output
open x
open y
open z
close z
close y
end
close x

Hints

Hint 1

The constructor prints open, and the destructor prints close.

Hint 2

Curly brackets create a new scope.

Hint 3

Objects are destroyed in reverse order.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

class Guard {
    string name_;

public:
    Guard(const string& name) : name_(name) {
        cout << "open " << name_ << endl;
    }
    ~Guard() {
        cout << "close " << name_ << endl;
    }
};

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    Guard first(a);
    {
        Guard second(b);
        Guard third(c);
    }
    cout << "end" << endl;
    return 0;
}

Lesson: Modern C++ →