Systems CourseC/C++ · Linux · Memory
C++ CoreLesson 12 of 441 min read6 questions

Destructors & RAII

Automatic cleanup; virtual for polymorphic bases; Rule of 3/5.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. ~ClassName(), no params/return, exactly one. Runs at end of scope (stack) or on delete (heap). Members destroyed in reverse order; derived dtor before base.
  2. RAII: tie a resource's lifetime to an object's lifetime → cleanup is automatic and exception-safe.
  3. Virtual destructor required on any polymorphic base: delete a derived object via a base pointer with a non-virtual dtor = UB / leak.
  4. Rule of 3/5: custom dtor ⇒ likely need custom copy ctor + copy assignment (+ move ops in C++11), else shallow copy → double-free.

Why RAII is the C++ way

Wrap a resource in an object whose destructor releases it. On scope exit — even via an exception — cleanup runs automatically. std::unique_ptr, std::lock_guard, std::fstream all use this.

Watch out

Easily confused

virtual vs non-virtual destructor
Delete a derived via base pointer: virtual dtor → full cleanup; non-virtual → only the base part destroyed = UB/leak.
shallow vs deep copy
Shallow copy duplicates the pointer (two owners → double-free). Deep copy duplicates the pointed-to data. Rule of 3/5 handles this.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.