# Ownership

> Why everything in the framework is owned by something that releases it — textures, objects, scenes, callbacks, behaviors — why its API has no raw pointer, what you keep across frames, and why Callback exists instead of std::function.

Source: https://omardev29.github.io/rmp-docs/framework/why/ownership.html

Everything the framework hands you is owned by something that releases it at the right moment, and you never free anything yourself. A texture lets go of the GPU when the last copy of it goes; an object is freed by its scene; a scene by the stack; a callback by the object that holds it. There is no `Unload` to remember, no `delete` to write, and no order to get right on the way out.

The framework holds itself to it. No owning raw pointer appears in its headers or its sources, and no bare `new`, `delete`, `malloc` or `free`: `tools/ownership_check.sh` rejects them, and its list of exceptions only ever gets shorter. The two left are where raylib's C interface hands a buffer across and frees it itself.

## What owns what

Inside the framework, the choice of how to hold something follows one order of preference, from first choice to last:

| Form | When |
|---|---|
| a value | whatever fits: a `Vector2`, a [`Shape`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#Shape), a behavior, an options struct |
| `T &` | something that certainly exists and keeps its identity for the length of the call |
| `std::span<T>`, `std::string_view` | the caller's elements, or the caller's text, for the length of the call |
| [`rmp::Ref<T>`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Ref.html) | something that may not be there and is not yours, within the frame |
| [`rmp::Handle<T>`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html) | an object that can die, kept across frames |
| `std::unique_ptr<T>` | sole ownership of something polymorphic or large |

There is no `T *` in that list, and no C string: a game names neither in the API, and the rest of the framework is held to the same rule. [Pointers and RAII](https://omardev29.github.io/rmp-docs/guidelines/pointers-and-raii.html), in the Guidelines, says why, what to write in each case instead, the few places a pointer is allowed, and which tools refuse one where.

The optional reference is the one form of the framework's own. 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`:

```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);
```

[`get<B>()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#get) hands one back, empty when the object has no `B`, and so does [`Handle::get()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html#get), empty once the object is gone. It is not a `T *`, which cannot say whether it may be null or whose it is, and not a `std::optional<std::reference_wrapper<T>>`, which says the same for the price of `<functional>` in every file with an object in it, and reads as `health->get().hp`.

Where there is always an answer, the answer is a reference: [`scene()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#scene) is a `Scene &`, because a spawned object always has its scene. And a field that names an object is a handle, as [`RayQuery::ignore`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#RayQuery-ignore), the object a ray passes through, is the shooter's `handle()`. None of them is yours to free. Where the framework does take ownership of something, it takes a `std::unique_ptr`, so the hand-over is written in the signature.

## Assets

An [`rmp::Texture`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#Texture) — like a `Font`, `Sound`, `Music`, `Shader` or `RenderTexture` — is a counted reference to one loaded resource. Copying it is one more reference; the last one to go unloads it. Loading the same name twice gives the same texture back with the count at two, which is what lets a hundred enemies share one sprite without anyone deciding who owns it.

```cpp
rmp::Texture _rabbit;

void _ready() override { _rabbit = rmp::assets::load_texture("rabbit.png"); }
void _draw() override { DrawTexture(_rabbit, 100, 100, WHITE); }
```

It converts to the raylib type it wraps, so every raylib function takes it. But only a variable converts. A temporary does not, because the texture would be unloaded at the end of the line and the raylib struct you kept would point at nothing:

Does not compile

```cpp
Texture2D player = rmp::assets::load_texture("player.png");
DrawTexture(player, 0, 0, WHITE);
```

The compiler refuses it, saying among other things: `deleted function`

Ownership is also what makes the way out safe. A texture belongs to the GPU context, and the context belongs to the window: unloading a texture after `CloseWindow()` is a write to something that no longer exists. Because every texture is held by something with a lifetime — a scene, an object, a global — the framework can release them in an order that works: the scenes and their objects first, then the globals, then whatever is still loaded, and only then the window.

## Objects, and the handle that outlives them

A scene owns its objects. [`spawn()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#spawn) makes one, the scene keeps it, and what you get back is a reference that is good for the rest of the frame, because an object that is destroyed is only freed when the frame ends.

Kept until the next frame, that reference can dangle. What you keep instead is a handle:

```cpp
class Turret : public rmp::Object {
public:
    rmp::Handle<rmp::Object> target;

    void _update(float) override {
        auto aim = target.get();
        if (!aim) return; // it died, or there never was one
        rotation = Vector2Angle({ 1, 0 }, Vector2Subtract(aim->position, position)) * RAD2DEG;
    }
};
```

A handle is the object's slot and that slot's generation. When the object dies the generation goes up, so the handle is empty from then on — and it stays dead even after the slot holds a new object, which is the classic bug of keeping an index. Checking a handle is an integer comparison. A handle can be typed, `handle<Goblin>()`, so the field you read after the check needs no cast.

## Scenes and globals

The scene stack owns its scenes. `RMP_GAME` makes the first one, and [`change()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Scene.html#change), `push()` and `replace()` make the next ones with `std::make_unique` and move them in on the same line, so no code of yours ever holds a scene by pointer.

[`rmp::global<T>()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#global) is the state that outlives a scene change: one instance per type, made the first time it is asked for, owned by the framework and destroyed on the way out — in reverse order of first use, after the scenes and before the window, so a global can hold a texture.

## Callbacks: why not std::function

A function you hand to the framework — an `on_collision`, an `on_click`, the `on_` fields of the behaviors — is kept in an [`rmp::Callback`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Callback.html), not a `std::function`, and there are two reasons.

The first is ownership. `std::function` has to be able to copy what it holds, so a lambda that owns something only it should own cannot go into one:

Does not compile

```cpp
#include <functional>
#include <memory>

std::function<void()> on_win = [save = std::make_unique<int>(3)] { (void)save; };
```

The compiler refuses it, saying among other things: `copy-constructible`

A `Callback` moves and never copies, so the same lambda is fine:

```cpp
auto &coin = spawn({ .position = { 400, 225 }, .size = { 16, 16 } });
auto bonus = std::make_unique<int>(10);
coin.on_collision([bonus = std::move(bonus)](rmp::Object &self, rmp::Object &) {
    score += *bonus;
    self.destroy();
});
```

The second is cost: `<functional>` is expensive to include, and every file with an object in it would pay for it. A `Callback` is what the framework actually needs — the captured state behind a shared pointer that carries its own destructor, and one function pointer to call it — and nothing else. Setting it again replaces what it held, and destroys what that captured.

## Behaviors

A behavior added to an object belongs to the object. [`add<B>()`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Object.html#add) moves it into storage that never moves it again, so the reference it returns, and the `rmp::Ref` `get<B>()` returns, stay good for as long as the behavior is attached. Removing the behavior, or destroying the object, runs its `_end` and frees it. A behavior's type is never erased into a `void *` you would have to delete: the storage holds it in a shared pointer that knows its destructor.
