Thuta Learning
C++
AdvancedProgrammingbeginner

RAII & Smart Pointers

What you'll walk away with

  • Explain the type, lifetime, and runtime behavior of RAII & Smart Pointers
  • Use warnings and sanitizers to test failure cases
  • Write modern and safer C++

Understand RAII & Smart Pointers as a contract about object lifetime, ownership, borrowing, invalidation, and exception safety—not merely syntax. Prefer RAII value types and smart pointers over raw owning new and delete so dangling access and double release are prevented by design.

Build a Complete Mental Model

Understand RAII & Smart Pointers as a contract about object lifetime, ownership, borrowing, invalidation, and exception safety—not merely syntax. Prefer RAII value types and smart pointers over raw owning new and delete so dangling access and double release are prevented by design.

Apply It in Modern C++

Build an original RAII & Smart Pointers example with `-std=c++23 -Wall -Wextra -Wpedantic` and test empty, boundary, invalid, and failure cases. Run lifetime-sensitive code under AddressSanitizer and UndefinedBehaviorSanitizer.

After This Lesson

cpp
#include <iostream>
#include <memory>

struct Resource {
    ~Resource() { std::cout << "released\n"; }
};

int main() {
    auto resource = std::make_unique<Resource>();
    std::cout << "owned\n";
}
You should see
owned
released

Try It Yourself

Build an original RAII & Smart Pointers example with `-std=c++23 -Wall -Wextra -Wpedantic` and test empty, boundary, invalid, and failure cases. Run lifetime-sensitive code under AddressSanitizer and UndefinedBehaviorSanitizer.

Memory and Safety Warning

Assuming one correct output proves lifetime, bounds, ownership, and undefined behavior are all correct.

C++ Core GuidelinesStandard C++ Foundation

Easy traps

  • Assuming one correct output proves lifetime, bounds, ownership, and undefined behavior are all correct.
  • Assuming a raw pointer or iterator remains valid after its owning container or resource changes.

Hands-on Exercise

Build an original RAII & Smart Pointers example with `-std=c++23 -Wall -Wextra -Wpedantic` and test empty, boundary, invalid, and failure cases. Run lifetime-sensitive code under AddressSanitizer and UndefinedBehaviorSanitizer.

You'll know it worked when: owned released