A destructor is a C++ member function that runs when an object is destroyed, releasing resources and performing cleanup. Destructors also participate in the automatic operations that occur when objects move through containers such as vectors. section 6.2.2
Destructors belong to C++ copy and lifetime management:
- The destructor, copy constructor, and copy assignment operator form the Big Three. section 6.2.2
- Adding the move constructor and move assignment operator extends this group to the Big Five. section 6.2.2
- Explicitly implementing one of these functions is presented as a reason to consider implementing all three, because copying and assignment must remain consistent. section 6.2.2
Instrumenting Date objects
Adding output to Date's constructors, copy operations, assignment operator, and destructor reveals repeated copies and destructions during vector append, insertion, removal, and printing. The output exposes hidden work and memory allocations or deallocations that can hurt performance. section 6.2.2
Listing 6.13 (Program 6.8 SurpriseVector-2): Date.h (instrumented)
#include <iostream>
#include <string>
using namespace std;
class Date
{
public:
Date() : year(2000), month(1), day(1)
{
cout << "(default constructor) " << endl;
}
Date(const int y, const int m, const int d)
: year(y), month(m), day(d)
{
cout << "(regular constructor) "; print(); cout << endl;
}
Date(const Date& other)
{
cout << "(copy constructor) "; other.print(); cout << endl;
year = other.year; #1
month = other.month; #1
day = other.day; #1
}
Date& operator =(const Date& other)
{
cout << "(assignment operator) "; other.print();
cout << endl;
if (this == &other) return *this;
year = other.year; #2
month = other.month; #2
day = other.day; #2
return *this;
}
~Date()
{
cout << «(destructor) «; print(); cout << endl;
}
void print() const;
private:
static const string MONTH_NAMES[13];
int year, month, day;
};
#1 Explicit member-by-member copying
#2 Explicit member-by-member assignments
Inspect the instrumented Date implementation and its destructor-related diagnostics. section 6.2.2


