A destructor is a special member function that runs when an object is destroyed. It has the same name as the class with a leading ~, no parameters, and no return type:
class Logger {
public:
Logger() { std::cout#include <iostream> << "created\n"; }
~Logger() { std::cout#include <iostream> << "destroyed\n"; }
};For an object on the stack, the destructor runs when the object goes out of scope:
void run() {
Logger log; // Prints "created".
} // Prints "destroyed".For an object allocated with new, the destructor runs when delete is called:
Logger* log = new Logger; // Prints "created".
delete log; // Prints "destroyed".Destructors are used to release resources the object acquired, such as memory from new:
class Buffer {
public:
Buffer() : data(new int[8]) {}
~Buffer() { delete[] data; }
int* data;
};
void run() {
Buffer buf;
} // ~Buffer runs and internally frees data.If no destructor is written, the compiler generates one that does nothing beyond destroying each field.
Dan