Language 2 of 10 · Topic 0.3

Variable Scoping, RAII, References (&) vs Pointers (*)

1Concept

C++ features References (type&), which are non-reseatable aliases to existing objects that cannot be null. RAII (Resource Acquisition Is Initialization) ties resource lifetime (files, mutexes, heap memory) strictly to stack variable scope, automatically invoking destructors upon block exit.

2Architecture Diagram

Scope Entry {
  RAII Object Created on Stack ──► Acquires Resource (Heap/Socket/File)
} Scope Exit } ──► Destructor Automatically Invoked! Releases Resource (Zero Leaks)

3Code Example

Stage 0 Language Foundations
#include <iostream>

class ScopedTimer {
    std::string tag;
public:
    ScopedTimer(std::string name) : tag(name) {
        std::cout << "[RAII] Acquired resource: " << tag << "\n";
    }
    ~ScopedTimer() {
        std::cout << "[RAII] Destructor called! Released resource: " << tag << "\n";
    }
};

void demo_scope() {
    ScopedTimer timer("Database Connection Pool");
    std::cout << "Inside function body doing work...\n";
} // timer destructor runs automatically here!

int main() {
    std::cout << "Calling demo_scope():\n";
    demo_scope();
    std::cout << "demo_scope() finished execution.\n";
    return 0;
}

4Expected Output

Calling demo_scope():
[RAII] Acquired resource: Database Connection Pool
Inside function body doing work...
[RAII] Destructor called! Released resource: Database Connection Pool
demo_scope() finished execution.

5Key Takeaways

  • RAII ensures guaranteed cleanup even if exceptions are thrown.
  • References (&) cannot be null and cannot be reseated after initialization.
  • Avoid raw new and delete in modern C++; rely on RAII and smart pointers.