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 turn: complete the destructor so the program prints the three lines shown in the tests.

Next: Order of destruction