---
description: Memory and Ownership
alwaysApply: false
---

# Memory and Ownership

RAII is the foundation. Smart pointers express ownership. Raw pointers mean "non-owning."

## Smart Pointer Rules

- **`std::unique_ptr`** — single ownership, zero overhead, default choice
- **`std::shared_ptr`** — shared ownership (rare), atomic ref count overhead
- **Raw pointer/reference** — non-owning observation only, never delete

```cpp
auto widget = std::make_unique<Widget>(42);
auto shared = std::make_shared<Resource>();
auto new_owner = std::move(widget); // Explicit ownership transfer
```

## RAII

Resource lifetime = object lifetime. No cleanup code at call sites — ever.

```cpp
class DatabaseConnection {
    sqlite3* db_ = nullptr;
public:
    explicit DatabaseConnection(const std::string& path) {
        if (sqlite3_open(path.c_str(), &db_) != SQLITE_OK)
            throw std::runtime_error("Failed to open database");
    }
    ~DatabaseConnection() { if (db_) sqlite3_close(db_); }
    DatabaseConnection(DatabaseConnection&& o) noexcept
        : db_{std::exchange(o.db_, nullptr)} {}
};
```

## Rule of Zero / Five

- **Rule of Zero**: prefer classes needing no custom special members (use smart pointers/containers)
- **Rule of Five**: if you define one special member, define all five (dtor, copy ctor/assign, move ctor/assign)

## Move Semantics

- Move constructors/assignment must be `noexcept` (vectors copy instead of move otherwise)
- Use `std::exchange` to null out moved-from resources
- Return by value from functions — NRVO or move, never copies

## std::span (C++20)

```cpp
void process(std::span<const int> data); // Non-owning view, works with vector/array/C-array
```

## Memory Safety Checklist

- No owning raw pointers — use smart pointers
- No dangling references — don't return references to locals
- No use-after-move — treat moved-from objects as empty
- No out-of-bounds — use `.at()` or `std::span`

## Anti-Patterns

- **`new` without smart pointer** — use `std::make_unique<T>()`
- **Manual `delete`/`delete[]`** — RAII, smart pointers, containers
- **C-style `malloc`/`free`/`realloc`** — use containers and smart pointers
