Skip to content

Module 5 · Classes and Objects — topic 3 of 5

Destructors and RAII

Destructors run automatically when objects die. Learn destruction order and RAII — tying resource lifetime to object lifetime — plus the Rule of Three/Five/Zero.

Beginner 15 min read·Lesson 19 of 40 in C++ Programming

Learning objectives

  • Write destructors and predict when they run
  • Apply RAII to files, memory and locks
  • Explain the Rule of Three/Five/Zero

Definition

A destructor (~ClassName()) is a special member function called automatically when an object's lifetime ends; RAII (Resource Acquisition Is Initialisation) is the idiom of acquiring a resource in a constructor and releasing it in the destructor.

Introduction

In C you must remember to fclose, free and unlock on every path out of a function. In C++ you wrap the resource in an object whose destructor releases it; leaving the scope — normally, by return or by an exception — runs the destructor automatically.

Why it matters

RAII is the single most important C++ idiom; it is how std::vector, std::string, std::fstream, std::unique_ptr and std::lock_guard work.

It makes leaks practically impossible and keeps code exception-safe.

Detailed explanation

A local object's destructor runs when execution leaves its scope. Objects are destroyed in reverse order of construction.

Members are destroyed after the destructor body runs, in reverse declaration order.

Rule of Three: if a class needs a custom destructor, copy constructor or copy assignment, it probably needs all three. Rule of Five adds move constructor and move assignment. Rule of Zero: prefer members that manage themselves (vector, string, unique_ptr) so you need none of them.

Destructors should not throw; they are implicitly noexcept.

Syntax

C++
class FileGuard {
public:
explicit FileGuard(const char* path) : f_(std::fopen(path, "w")) {}
~FileGuard() { if (f_) std::fclose(f_); }
FileGuard(const FileGuard&) = delete; // not copyable
FileGuard& operator=(const FileGuard&) = delete;
std::FILE* get() const { return f_; }
private:
std::FILE* f_;
};
  • The destructor has no parameters and no return type.
  • = delete forbids copying a resource owner that can't be shared.
  • There is exactly one destructor per class.

Code examples

Destruction order

C++
#include <iostream>
#include <string>
class Tracer {
public:
explicit Tracer(std::string n) : name_(std::move(n)) { std::cout << "construct " << name_ << '\n'; }
~Tracer() { std::cout << "destroy " << name_ << '\n'; }
private:
std::string name_;
};
int main() {
Tracer a("A");
{
Tracer b("B");
Tracer c("C");
}
std::cout << "end of main\n";
return 0;
}
Output
construct A
construct B
construct C
destroy C
destroy B
end of main
destroy A

Destructors run on early return

C++
#include <iostream>
struct Lock {
Lock() { std::cout << "locked\n"; }
~Lock() { std::cout << "unlocked\n"; }
};
int work(int x) {
Lock guard;
if (x < 0) return -1; // guard still unlocks
return x * 2;
}
int main() {
std::cout << work(-5) << '\n';
return 0;
}
Output
locked
unlocked
-1

More examples

An RAII buffer following the Rule of Five

C++
#include <cstring>
#include <iostream>
#include <utility>
class Buffer {
public:
explicit Buffer(std::size_t n) : size_(n), data_(new char[n]{}) {}
~Buffer() { delete[] data_; }
Buffer(const Buffer& o) : size_(o.size_), data_(new char[o.size_]) { std::memcpy(data_, o.data_, size_); }
Buffer& operator=(Buffer o) { swap(o); return *this; } // copy-and-swap
Buffer(Buffer&& o) noexcept : size_(o.size_), data_(o.data_) { o.size_ = 0; o.data_ = nullptr; }
void swap(Buffer& o) noexcept { std::swap(size_, o.size_); std::swap(data_, o.data_); }
std::size_t size() const { return size_; }
char* data() { return data_; }
private:
std::size_t size_;
char* data_;
};
int main() {
Buffer a(16);
std::strcpy(a.data(), "hello");
Buffer b = a; // deep copy
b.data()[0] = 'J';
Buffer c = std::move(a); // steal a's memory
std::cout << c.data() << ' ' << b.data() << ' ' << a.size() << '\n';
return 0;
}
Output
hello Jello 0

Step-by-step explanation

  • The constructor allocates; the destructor frees — no manual delete anywhere else.
  • The copy constructor allocates new memory and copies the bytes (a deep copy), so changing b leaves a alone.
  • The move constructor takes a's pointer and leaves a empty, so the memory is freed exactly once.
  • Copy-and-swap gives a correct, exception-safe assignment operator.

Expected output

Running “An RAII buffer following the Rule of Five” prints exactly:

TextOutput
hello Jello 0

Practical applications

  • std::fstream closes files in its destructor.
  • std::lock_guard releases mutexes automatically.
  • Database and network libraries close connections in destructors.

Best practices

  • Follow the Rule of Zero whenever possible.
  • Wrap every raw resource in an RAII class.
  • Delete copy operations for non-copyable resources.

Common mistakes

Shallow copy of an owning pointer

Avoid

class S { char* p; public: S() : p(new char[10]) {} ~S() { delete[] p; } };
S a; S b = a; // double delete

Prefer

class S { std::vector<char> p = std::vector<char>(10); }; // Rule of Zero

The default copy copies the pointer, so both objects delete the same memory. Use self-managing members.

Throwing from a destructor

Avoid

~Conn() { if (!close()) throw std::runtime_error("x"); }

Prefer

~Conn() { if (!close()) std::cerr << "close failed\n"; }

Destructors are noexcept; throwing terminates the program.

Important notes

  • Objects created with new are destroyed only when delete is called — which is why owning raw pointers break RAII unless wrapped in smart pointers.
  • Static objects are destroyed after main returns, in reverse order of construction.

Key takeaways

  • Destructors run automatically at the end of an object's lifetime.
  • RAII ties resource release to scope exit.
  • Rule of Zero: let members manage resources.

Try it yourself

  1. 1
    Write a Timer class that prints how many loop iterations ran between construction and destruction (pass the count in).
  2. 2
    Add tracing output to the Buffer class to show which special member function runs for each line in main.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

7 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat does RAII stand for?
  • ModerateWhat is printed?
Practise this topic