# Pointers and RAII

> No raw pointer anywhere — what to write instead, the few places one is allowed and why — and nothing owned by hand: every resource freed by the thing that holds it. Each mistake shown with what refuses it.

Source: https://omardev29.github.io/rmp-docs/guidelines/pointers-and-raii.html

No raw pointer: not in what the framework hands a game, not in its own sources, not in its tests or its examples. And nothing freed by hand: whatever is owned is owned by something that frees it when it goes. The two rules are one idea from two sides — every thing has an owner you can see, and everything that refers to it says how.

## Why no raw pointer

A pointer asks whoever reads it three questions — may it be null, who owns what it points at, how long does that live — and its type answers none of them. Each form below answers all three, so a signature written with them needs no comment to be used right. [Google's guide](https://omardev29.github.io/rmp-docs/guidelines/google.html#pointers) allows a pointer for an optional argument or a result that may be missing; this framework does not, and has a type for each of those cases instead.

## What to write instead

| What you mean | What you write |
|---|---|
| a small thing, copied | the value: a `Vector2`, a [`Shape`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#Shape), an options struct |
| a result that may not be there | `std::optional<T>` |
| an argument that may be left out | two overloads: [`load_map(name)`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-assets.html#load_map) and `load_map(name, level)` |
| something that is certainly there, for the length of the call | `T &` |
| the caller's elements, for the length of the call | [`std::span<T>`](https://omardev29.github.io/rmp-docs/guidelines/pointers-and-raii.html#spans) |
| the caller's text, for the length of the call | [`std::string_view`](https://omardev29.github.io/rmp-docs/guidelines/strings.html) |
| something that may be missing and is not yours, within the frame | [`rmp::Ref<T>`](https://omardev29.github.io/rmp-docs/guidelines/pointers-and-raii.html#ref) |
| an object kept from one frame to the next | [`rmp::Handle<T>`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html) |
| something that is yours alone | a value, or a `std::unique_ptr<T>` when it is polymorphic or large |

### A reference, for what is there

Compiles; `rmp lint` refuses it: `custom-rmp-raw-pointer`

```cpp
void reset(int *score) { *score = 0; }
```

```cpp
void reset(int &score) { score = 0; }
```

The framework's API reads the same way. A spawned object always has its scene, so [`scene()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#scene) is a `Scene &`; a control that edits a value takes it by reference, as [`slider`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html#slider) does.

### `std::optional`, for an answer that may not be there

Compiles; `rmp lint` refuses it: `custom-rmp-raw-pointer`

```cpp
const Door *first_open(const std::vector<Door> &doors) {
    for (const Door &door : doors) {
        if (!door.locked) return &door;
    }
    return nullptr;
}
```

```cpp
#include <optional>

std::optional<Vector2> first_open(const std::vector<Door> &doors) {
    for (const Door &door : doors) {
        if (!door.locked) return door.position;
    }
    return std::nullopt;
}
```

And what reads it asks first. `*` on an empty `std::optional` is undefined behaviour, not an error, so clang-tidy refuses a read that nothing before it has checked:

Compiles; `rmp lint` refuses it: `bugprone-unchecked-optional-access`

```cpp
const std::optional<Vector2> door = first_open();
DrawCircleV(*door, 8, GREEN);
```

```cpp
if (const std::optional<Vector2> door = first_open()) DrawCircleV(*door, 8, GREEN);
```

### `std::span`, for the caller's elements

A pointer and a count are two arguments that have to agree, and nothing makes them. A `std::span` is the two in one, from a `std::array`, a `std::vector` or a list written in place.

Compiles; `rmp lint` refuses it: `custom-rmp-raw-pointer`

```cpp
float average(const float *values, const int count) {
    float sum = 0;
    for (int i = 0; i < count; ++i) sum += values[i];
    return count > 0 ? sum / static_cast<float>(count) : 0;
}
```

```cpp
#include <span>

float average(std::span<const float> values) {
    float sum = 0;
    for (const float value : values) sum += value;
    return values.empty() ? 0 : sum / static_cast<float>(values.size());
}
```

It works the other way too: [`raycast_all`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#raycast_all) writes every hit along a ray into a span of yours, as many as it holds, and says how many it wrote.

```cpp
std::array<rmp::RayHit, 8> hits{};
const int count = raycast_all({ .from = { 0, 200 }, .to = { 800, 200 } }, hits);
DrawText(TextFormat("%d in the way", count), 10, 10, 20, WHITE);
```

### `rmp::Ref`, for something that may be missing

An [`rmp::Ref<T>`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Ref.html) is empty, or refers to something; it owns nothing, and asking it is an `if`. It is what [`get<B>()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#get) hands back, empty when the object has no `B`, and what [`Handle::get()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html#get) hands back, empty once the object is gone. Keep it within the frame; across frames, keep the handle.

Compiles; `rmp lint` refuses it: `custom-rmp-raw-pointer`

```cpp
rmp::behavior::Health *health_of(rmp::Object &object) {
    if (auto health = object.get<rmp::behavior::Health>()) return &*health;
    return nullptr;
}
```

```cpp
auto &player = spawn({ .size = { 26, 26 } });
player.add<rmp::behavior::Health>({ .hp = 3 });

if (auto health = player.get<rmp::behavior::Health>()) health->heal(1);
```

Reaching into an empty one without asking is a mistake in the game, and the framework says so once, in the log; the line that forgot the `if` then writes to a stand-in made for the purpose instead of taking the game down. `[dev] strict` stops a debug build there instead, and a type with no default constructor has no stand-in: there, the one mistake ends the program.

It is a type of the framework's own because the standard library's spelling, `std::optional<std::reference_wrapper<T>>`, costs `<functional>` in every file with an object in it, and reads `health->get().hp`.

### In a public header

Everything a game can name — every function, field, variable and alias in `include/rmp/` outside a `detail` namespace and outside a private member — is read by `tools/pointer_check.py`: clang dumps each header's declarations and the script refuses a pointer, a C string, or an alias that hides one. Reading the declarations and not the text is the point: a comment is not a declaration, a private member is not public, and `using SampleFn = ...` is seen through.

Compiles; `rmp test pointers` refuses it

```cpp
#pragma once

#include <string_view>

namespace rmp {
class Object;

Object *find(std::string_view name);
} // namespace rmp
```

```cpp
#pragma once

#include <string_view>

namespace rmp {
class Object;
template <class T> class Ref;

Ref<Object> find(std::string_view name);
} // namespace rmp
```

## Where a pointer is allowed

Nowhere but here, and each place for a reason:

- **A type of a C library the framework speaks to** — Clay, cJSON, cute_tiled, cute_aseprite, rres. Their API is pointers, and that is not a choice the framework made.
- **An `extern "C"` function** and its parameters: a fuzzer's entry point takes its input as a pointer, because that is its C interface.
- **`operator->`**, which the language requires to return one. It is how `health->hp` reads, on a `Ref` and on a `Handle`.
- **Inside `rmp::Ref`**: its one member is the optional reference, so that nothing else has to hold one.
- **C**: a `.c` file — the resource packer, the plain C example, the sanitizer hooks — is C because it has to be, and C has nothing else.

raylib is not on the list. A raylib function that takes an address takes it in a call, and an address in a call is not a pointer anybody declared:

```cpp
Camera3D camera = { .position = { 10, 10, 10 }, .up = { 0, 1, 0 }, .fovy = 45 };
UpdateCamera(&camera, CAMERA_ORBITAL);
```

The rule is newer than some of the code. In the public headers, the pointers a game cannot reach — in a `detail` namespace or a private member — are listed in `tools/pointer_ratchet.txt`, each with its reason, and the list only shrinks: a new one fails until it is replaced or written down, and a line that matches nothing any more fails too.

Everywhere else — the framework's sources, its tests, its examples — what the code still owes the rule is counted, file by file, in `tools/lint_debt.txt`. `rmp lint` fails a pointer that is not owed there, and a count that grew; the counts only go down.

## RAII: the owner frees it

What is owned is a value or a `std::unique_ptr`, and it is freed by its destructor: no `new`, no `delete`, no `malloc`, no `free`. A `delete` nobody wrote cannot be forgotten, and one nobody wrote cannot run twice. The order of the way out is the order the owners go, which is what makes it safe to free a texture before the window that its memory belongs to.

Two files of the framework allocate with the C allocator, and `tools/ownership_check.sh` names them with the reason: raylib's file-loading callback and the resource pack's reader hand raylib bytes that raylib frees itself, with `UnloadFileData()`. That is raylib's C interface, not an ownership the framework chose, and the list only shrinks.

Compiles; `rmp lint` refuses it: `cppcoreguidelines-owning-memory`

```cpp
int wave_hp() {
    auto *boss = new Enemy();
    const int hp = boss->hp;
    delete boss;
    return hp;
}
```

```cpp
int wave_hp() {
    const Enemy boss;
    return boss.hp;
}
```

When it has to be on the heap — something polymorphic, or too big to move about — it is a `std::unique_ptr`, made with `std::make_unique`, and the hand-over is written in the signature. That is how a scene is made: [`change()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#change) makes the next one with `std::make_unique`, and the stack owns it from there.

```cpp
#include <memory>

struct State {
    virtual ~State() = default;
    [[nodiscard]] virtual float speed() const = 0;
};

struct Walking : State {
    [[nodiscard]] float speed() const override { return 120.0f; }
};

std::unique_ptr<State> first_state() { return std::make_unique<Walking>(); }
```

### A raylib resource has an owner too

raylib hands out textures, sounds and fonts that are freed by a matching `Unload`. In a scene, an object or an example, a forgotten one is a leak and a second one is a double free, so a raylib `Load*` or `Unload*` appears only in the few files of the framework that own what it makes. A game loads through `rmp::assets`, which hands back a handle that frees the resource when its last copy goes:

Compiles; `rmp test ownership` refuses it: `O2`

```cpp
const Texture2D rabbit = LoadTexture("rabbit.png");
DrawTexture(rabbit, 100, 100, WHITE);
UnloadTexture(rabbit);
```

```cpp
const rmp::Texture rabbit = rmp::assets::load_texture("rabbit.png");
DrawTexture(rabbit, 100, 100, WHITE);
```

[Ownership](https://omardev29.github.io/rmp-docs/framework/why/ownership.html) has what owns what in the framework — assets, objects and their handles, scenes, globals, callbacks — and why a callback is an `rmp::Callback` and not a `std::function`.

### What you open closes itself

RAII is not only for memory. A container of the UI is opened by the function that takes its body and closed by a guard in that same function. The body is a lambda, so a `return` in it ends the body and not the container, and the guard closes the container even if the body throws: one left open would spoil the whole frame.

```cpp
rmp::ui::panel([&] {
    rmp::ui::text("Paused");
    if (rmp::ui::button("Resume")) resume();
    if (rmp::ui::button("Quit")) quit();
});
```

## Who checks what

| Rule | Tool | Where |
|---|---|---|
| No raw pointer and no C string in a declaration a game can name | `tools/pointer_check.py`, `rmp test pointers`, against `tools/pointer_ratchet.txt` | the declarations in `include/rmp/` |
| No raw pointer anywhere else | `custom-rmp-raw-pointer`, a query of the framework's `.clang-tidy`; `rmp lint`, against `tools/lint_debt.txt` | `src/`, `tests/`, `examples/`, and the bodies of the headers' inline functions |
| A `std::optional` is asked before it is read | `bugprone-unchecked-optional-access`; `rmp lint` | `src/`, `tests/`, `examples/` |
| No `new`, `delete`, `malloc` or `free` | `tools/ownership_check.sh` O1, `rmp test ownership` | `include/rmp/` and `src/rmp/` |
| The same, as clang-tidy sees it | `cppcoreguidelines-owning-memory` and `cppcoreguidelines-no-malloc`; `rmp lint` | `src/`, `tests/`, `examples/` |
| raylib's `Load*` and `Unload*` only in the files that own what they make | `tools/ownership_check.sh` O2, `rmp test ownership` | `include/rmp/`, `src/rmp/` and the examples' C++ |

`custom-rmp-raw-pointer` runs only with clang-tidy's `--experimental-custom-checks`, which `rmp lint` passes. A game gets none of these tools: the rules are recommended to it, and the clang-tidy checks among them hold it only if it [switches the framework's clang-tidy on](https://omardev29.github.io/rmp-docs/guidelines/index.html#switching-on-clang-tidy). [What checks what](https://omardev29.github.io/rmp-docs/guidelines/enforcement.html) has every rule of these pages in one table.
