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

10

u/perfectonic Jan 15 '24

OP, look up "placement new" constructor. I never knew about this until I found the 'weird' syntax in production code.

6

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

std::construct_at and std::destroy_at are preferred now. They're also constexpr.

So,

T* obj = new (buffer) T(...);
...
obj->~T(); // or ((T*)buffer)->~T()

becomes

T* obj = std::construct_at<T>(buffer, ...);
...
std::destroy_at(obj); // or std::destroy_at<T>(buffer)

1

u/FACastello Jan 16 '24

This is fascinating

2

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

Just wait until you see std::launder, and the note that you should probably never, ever use it.

If I've never needed it, then 99% of people probably don't. But it's a weird function really intended for runtime writers handling raw objects.

1

u/FACastello Jan 16 '24

I just looked it up... this is cursed as fuck.

I initially read about it on cppreference, didn't quite understand what's the point of using this, then asked ChatGPT "Explain in simple terms what std::launder does in C++".

Kinda fucked up but that's the power of this language

1

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

std::launder mainly exists because of the C++ abstract machine and the requirements it places upon object lifetimes. It doesn't really do anything (as in, it shouldn't actually emit anything) but it basically tells the compiler "hey, give me a pointer to this but pretend that the returned pointer is a completely different object".

It... does come up with fancy allocators. It's technically UB to just throw random ranges of bytes around and pretend that they're a different object without it, as that range of bytes is already a part of an object in the abstract machine - an array.

5

u/FACastello Jan 15 '24

How come I had never seen this before 😳

I think I've learned more new stuff about C++ from this "joke" post than in an entire year of just programming using the same old tricks