Constructors, destructors and RAII
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
An object has a lifetime
In C++, an object is created at a known point and destroyed at a known point. Nothing is left to a garbage collector. This predictability is the single most useful thing about the language, once you learn to lean on it.
Constructors
A constructor runs when an object is created. Its job is to put the object into a valid state. Use the member initialiser list to set fields.
#include <iostream>
#include <string>
class Book {
public:
Book(std::string title, int pages)
: title_{std::move(title)}, pages_{pages} {
std::cout << "Book created: " << title_ << "\n";
}
Book() : Book{"Untitled", 0} {} // delegating constructor
const std::string& title() const { return title_; }
private:
std::string title_;
int pages_;
};
The code above uses std::move, which needs <utility>; the move semantics lesson explains it. For now read it as "take the string without copying it again".
Why the initialiser list rather than assignment in the body? Because fields are always constructed before the body runs. If you write title_ = title; inside the body, the string is first default-constructed and then assigned: two steps instead of one. For references and const members the list is the only way, since they cannot be assigned later. Fields are initialised in the order they are declared in the class, not the order in the list. Keep the list in the same order, and the compiler will warn you when it is not.
Destructors
A destructor runs when the object's lifetime ends: when a local variable goes out of scope, when a container removes it, or when you delete it. It is named with a tilde.
#include <iostream>
class Noisy {
public:
explicit Noisy(int id) : id_{id} { std::cout << "construct " << id_ << "\n"; }
~Noisy() { std::cout << "destroy " << id_ << "\n"; }
private:
int id_;
};
int main() {
Noisy a{1};
{
Noisy b{2};
std::cout << "inner scope ending\n";
} // b destroyed here
std::cout << "main ending\n";
} // a destroyed here
The output is: construct 1, construct 2, inner scope ending, destroy 2, main ending, destroy 1. Objects are destroyed in the reverse order of creation. That reverse order is no accident; it is what makes cleanup safe when one object depends on another.
RAII: resource acquisition is initialisation
The odd name hides a simple idea. Tie a resource, such as memory, a file handle, a lock or a socket, to the lifetime of an object. The constructor acquires it. The destructor releases it. Then it is impossible to forget the release, even when the function returns early or throws an exception.
Here is a small file wrapper. The standard library already has std::ifstream and std::ofstream that work this way, but writing one yourself shows the mechanism.
#include <cstdio>
#include <stdexcept>
#include <string>
class File {
public:
File(const std::string& path, const char* mode)
: handle_{std::fopen(path.c_str(), mode)} {
if (!handle_) throw std::runtime_error("cannot open " + path);
}
~File() { if (handle_) std::fclose(handle_); }
File(const File&) = delete; // no copies: two owners would close twice
File& operator=(const File&) = delete;
void write(const std::string& text) { std::fputs(text.c_str(), handle_); }
private:
std::FILE* handle_;
};
void saveReport() {
File out{"report.txt", "w"};
out.write("line one\n");
if (/* something goes wrong */ false) throw std::runtime_error("failed");
out.write("line two\n");
} // file is closed here, whatever path we took
Compare that with the manual style where you call fclose at the end of the function. Every early return and every exception has to remember to close the file. Miss one and you leak a handle. With RAII the compiler guarantees the cleanup. The same pattern powers std::vector (frees its memory), std::lock_guard (releases a mutex) and std::unique_ptr (deletes what it owns).
The rule of zero, three and five
A class that owns a resource needs to decide what happens when it is copied or moved. The compiler generates five special functions if you do not: the destructor, copy constructor, copy assignment, move constructor and move assignment. The rules of thumb:
- Rule of zero: if your class holds only members that manage themselves (strings, vectors, smart pointers), write none of the five. The defaults do the right thing. This is the goal for almost all of your classes.
- Rule of five: if you write any one of the destructor, copy operations or move operations, you probably need to think about all five. Either define them, or delete the ones you do not want, as the
Fileclass did.
Why does this matter? Take a class holding a raw owning pointer, with the default copy. The copy gets the same pointer value. Both objects now think they own the memory, and both free it on destruction. That is a double free, and it crashes or corrupts memory. Deleting the copy operations, or using std::unique_ptr inside, prevents it.
The common mistake
Using new and delete by hand in ordinary code. Each new is a promise you must keep on every path. Throw an exception between them and the memory leaks. Put the memory inside an object instead: a vector for arrays, a unique_ptr for a single object. Another common error is throwing an exception from a destructor. Destructors run during stack unwinding, and a second exception at that moment terminates the program. Destructors should not throw.
Try it yourself
- Run the
Noisyexample and check the order of the messages. Then put threeNoisyobjects in astd::vectorand watch what is created, copied and destroyed. - Write a
Timerclass whose constructor records the start time withstd::chrono::steady_clockand whose destructor prints the elapsed milliseconds. Create one at the top of a function you want to measure. - Write a class that holds a
std::vector<int>and astd::string, and confirm it copies correctly without any special member functions.
#include <iostream>
#include <string>
class Book {
public:
Book(std::string title, int pages)
: title_{std::move(title)}, pages_{pages} {
std::cout << "Book created: " << title_ << "\n";
}
Book() : Book{"Untitled", 0} {} // delegating constructor
const std::string& title() const { return title_; }
private:
std::string title_;
int pages_;
};
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account