Chapter 17: Memory Management

Memory Management in C++: From Old-School new/delete to Modern, Safe, & Efficient Code

Hello my brilliant student! 🌟 Welcome to Lesson 17 β€” Memory Management β€” one of the most important, most powerful, and historically most error-prone topics in C++!

C++ gives you manual control over memory β€” that’s why it’s so fast and flexible, but also why it’s easy to make mistakes like:

  • Memory leaks (forgetting to delete)
  • Dangling pointers (using memory after delete)
  • Double-delete (crashing the program)
  • Use-after-free bugs

Today we’re going to learn:

  • The old way: new / delete
  • The modern, recommended way: smart pointers (unique_ptr, shared_ptr)
  • RAII β€” the golden principle that makes C++ safe and beautiful
  • Move semantics β€” rvalue references (&&) and std::move β€” the secret to zero-copy efficiency

We’ll go very slowly, with real-life analogies, tons of examples, common mistakes, and modern best practices (2026 style).

Let’s start!

1. The Old Way: Raw new / delete

C++

Problems with raw pointers:

  • Forget delete β†’ memory leak
  • Call delete twice β†’ double delete (crash or corruption)
  • Use pointer after delete β†’ dangling pointer (undefined behavior)
  • Wrong delete vs delete[] β†’ undefined behavior
  • Exception thrown before delete β†’ leak

Verdict (2026): Never use raw new/delete in modern C++ unless you’re writing very low-level library code.

2. RAII – Resource Acquisition Is Initialization (The Golden Rule)

RAII is the most important C++ idiom. It means: Resources (memory, files, locks, sockets…) are acquired in a constructor and released in the destructor β€” automatically!

When an object goes out of scope (end of block, function return, exception…), its destructor runs automatically β€” no manual cleanup needed.

Smart pointers are perfect RAII wrappers for dynamic memory.

3. Smart Pointers – The Modern, Safe Way

Include: #include <memory>

Smart Pointer Ownership When to use
std::unique_ptr Exclusive (only one owner) Default choice for single ownership
std::shared_ptr Shared (reference counting) When multiple objects need to share ownership
std::weak_ptr Non-owning reference to shared_ptr To break cycles or observe without owning

A. std::unique_ptr – Exclusive ownership (most common)

C++

Why make_unique is better than new:

  • Exception-safe
  • Cleaner
  • No risk of leak

B. std::shared_ptr – Shared ownership

C++

C. std::weak_ptr – Observe without owning

C++

Modern rule (2026):

  • Use unique_ptr for single ownership (90% of cases)
  • Use shared_ptronly when you really need shared ownership
  • Use weak_ptr to avoid circular references

4. Move Semantics – Zero-Copy Efficiency (C++11+)

Move semantics let us transfer ownership of resources (memory, file handles…) without copying β€” super fast!

Key concepts:

  • lvalue β€” has name, can take address (&x)
  • rvalue β€” temporary, no name (like 42, std::string(“hello”) + “world”)
  • rvalue reference (&&) β€” binds only to rvalues
C++

std::move – casts an lvalue to rvalue so move can happen:

C++

Rule: Always mark move constructors and move assignment operators as noexcept β€” STL containers require it for strong exception safety.

5. Full Practical Example – Safe & Efficient Vector-like Class

C++

Your Mini Homework (Try These!)

  1. Rewrite your earlier BankAccount class using std::unique_ptr for some internal resource (e.g., transaction log).
  2. Create a class that manages a dynamic array using move semantics β€” show copy vs move performance.
  3. Write a function that takes std::unique_ptr<T> by value (transfer ownership) and prints something.

You’re doing absolutely phenomenal! You’ve just mastered modern memory management β€” RAII + smart pointers + move semantics are what make C++ safe, fast, and elegant at the same time.

Next lesson: File I/O & Streams β€” reading/writing files, binary data, serialization β€” super useful for real-world apps!

Any questions? Confused about unique_ptr vs shared_ptr? Want more examples with move semantics or RAII in practice? Just ask β€” your friendly C++ teacher is right here for you! πŸš€

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *