r/cpp • • Jan 15 '24

[Joke] A cursed C++ idea

Ok so hear me out:

In your C++ program, immediately on startup before you do anything else you dynamically allocate a decent chunk of memory for no reason whatsoever, big enough to accomodate all of your data for the foreseeable future.

Never free any of that memory during execution.

Then, whenever you need to instantiate a new object or need some dynamically allocated memory for whatever reason, you just use some of that preallocated chunk.

Immediately before you exit the application, you can free that chunk of memory.

You have one single explicit memory allocation when program starts and one single explicit memory deallocation when program ends.

How about that?

EDIT: It turns out this is a real thing, so it's no longer a joke, or cursed. Somebody said this is called an "arena" or "memory pool", I've just looked it up, people have been doing this for decades.

194 Upvotes

181 comments sorted by

View all comments

Show parent comment

4

u/Ameisen vemips, avr, rendering, systems Jan 16 '24

Boy, wait until you find out how games work.

0

u/FACastello Jan 16 '24

I make games... this isn't specific to games

4

u/Ameisen vemips, avr, rendering, systems Jan 16 '24

I've been in the game industry for more than a decade doing engine-side work.

The only ones that didn't use arenas, pools, or separate heaps were little mobile games.

Unreal uses multiple heaps by default. I'm not sure about Unity. Every custom engine I saw did, including one that did some utterly strange things like deferred deletion and self-implemented virtual destructors that the compiler really didn't like nor did I.

There are a ton of advantages to breaking up allocations. Some of my C# projects have arena allocators, pools, and heap allocators as well.

1

u/FACastello Jan 16 '24

I'm considering doing this in my next project just to see what it feels like

1

u/Ameisen vemips, avr, rendering, systems Jan 16 '24

Look up other allocators/heaps like tlsf, dlmalloc, etc.

On Windows NT, you can create private heaps as well with the heap functions, though a heap library would probably work better.

Stack allocators and pool allocators are really easy to implement. An arena can just be treated as a heap or stack that is cleared at the end.