C/C++ Arena

Step 1 of 8

Destructors

In C, cleaning up (calling free, fclose, unlocking) was your job, on every path out of every function. Forget it once and you have a leak. C++ has a feature that changes everything: the destructor.

A destructor is a member function named ~ClassName() that runs automatically when an object's lifetime ends. For a local variable, that's when execution leaves the block ({ }) it was declared in, whatever the reason: reaching the end, return, or break.

#include <iostream>
#include <string>

struct Timer {
    std::string name;
    explicit Timer(std::string n) : name(n) { std::cout << "start " << name << "\n"; }
    ~Timer() { std::cout << "stop " << name << "\n"; }
};

int work(int x) {
    Timer t("work");
    if (x < 0) {
        return -1;
    }
    std::cout << "working on " << x << "\n";
    return x * 2;
}

int main() {
    work(5);
    work(-1);
    std::cout << "done\n";
}
start work
working on 5
stop work
start work
stop work
done

What to notice

This guarantee ("the destructor always runs when the object goes away") is the foundation of safe resource management in C++, which the next steps build on. The Watch it run link shows the output appearing as each object is created and destroyed.

Your task

Complete the destructor so the program prints the three lines shown in the tests.

Challenge 2

Complete the destructor so it prints leave and the guard's name. The program prints enter site A and then leave site A.

Challenge 3

Write a struct Timer whose constructor prints start and whose destructor prints stop. main is written for you; because t is created inside the loop body, it is destroyed at the end of every round. The output is:

start
round 1
stop
start
round 2
stop
done

Next: Order of destruction