> For the complete documentation index, see [llms.txt](https://nodejsdocs.gitbook.io/everthing-c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nodejsdocs.gitbook.io/everthing-c++/memory-management-in-performance-critical-c++-systems.md).

# Memory Management in Performance-Critical C++ Systems

This chapter offers a deep dive into how memory is managed in C++ and how to take control of it. You’ll explore stack vs heap allocation, dynamic memory, smart pointers, and move semantics — all essential for writing efficient, leak-free, and high-performance code.

***

### 1. Memory Management and the Stack

#### 1.1 What is Stack Memory?

* Automatically managed memory (LIFO).
* Fast allocation/deallocation.
* Limited size (usually 1MB to 8MB).
* Function-local variables are stored here.

```cpp
void example() {
    int x = 42; // Stored on stack
}
```

#### 1.2 When to Avoid Stack?

* Large arrays or objects.
* Lifetime must extend beyond the scope.

***

### 2. Dynamic Memory and the Free Store (Heap)

#### 2.1 What is Heap Memory?

* Managed manually (using `new`, `delete`).
* Slower allocation than stack.
* Required for dynamic lifetime.

```cpp
int* p = new int(42);  // Allocated on heap
*...*
delete p;              // Must free manually
```

#### 2.2 Risks:

* Memory leaks.
* Dangling pointers.
* Fragmentation.

***

### 3. Smart Pointers and `std::unique_ptr`

#### 3.1 What is a Smart Pointer?

* An object that manages a raw pointer and deletes it automatically.

#### 3.2 `std::unique_ptr`

* Exclusive ownership.
* Lightweight and zero overhead.

```cpp
#include <memory>
std::unique_ptr<int> ptr = std::make_unique<int>(42);
```

***

### 4. Shared Pointers: `std::shared_ptr`

* Reference counted.
* Shared ownership.
* More overhead than `unique_ptr`.

```cpp
#include <memory>
auto p1 = std::make_shared<int>(10);
auto p2 = p1; // shared ownership
```

#### Avoid in latency-critical paths.

***

### 5. Weak Pointers: `std::weak_ptr`

* Non-owning reference to `shared_ptr`.
* Used to break cyclic references.

```cpp
std::weak_ptr<int> weak_ref = p1;
if (auto shared = weak_ref.lock()) {
    // safe access
}
```

***

### 6. Copy Semantics and Return Value Optimization (RVO)

#### 6.1 Copy Constructor

Used when passing/returning by value.

```cpp
class Obj {
public:
    Obj(const Obj& other); // copy constructor
};
```

#### 6.2 RVO (Return Value Optimization)

Compiler eliminates copy/move when returning local objects.

```cpp
Obj create() {
    Obj obj;
    return obj; // No copy due to RVO
}
```

***

### 7. Move Semantics

#### 7.1 Move Constructor and Move Assignment

Transfers resources from one object to another without deep copy.

```cpp
class Obj {
public:
    Obj(Obj&& other); // move constructor
};

Obj a = std::move(b); // moves, doesn't copy
```

#### When to Use:

* Containers.
* Large memory structures.

***

### 8. Value Categories: L-Values and R-Values

#### 8.1 L-Value

* Has a persistent location (can appear on left of assignment).

#### 8.2 R-Value

* Temporary value, often moved.

```cpp
int x = 10;       // x is l-value
int y = x + 5;    // x+5 is r-value
```

***

### Tricky Questions and Tips

* **Q: Why prefer `std::unique_ptr` over `shared_ptr`?**\
  **A:** `unique_ptr` has zero ref-count overhead and deterministic destruction.
* **Q: What's the cost of shared\_ptr?**\
  **A:** 2 atomic increments/decrements per use. Can slow down multithreaded code.
* **Q: When is manual `new`/`delete` justified?**\
  **A:** When implementing custom memory pools or allocators.
* **Q: Can RVO be forced?**\
  **A:** Use `return obj;` directly or `std::move(obj)` with care.
* **Q: How does move constructor help containers?**\
  **A:** Enables vector reallocation with minimal copy overhead.

***
