Tuesday Coding Tip 16 — Creating objects in existing memory

2 5 32
calendar_todayschedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


C++ allows you to scrap your OS’ memory allocators, get yourself a huge chunk of memory and write your own allocators (they can be used with the standard library). It’s a hardcore optimization, but here’s a related tip that might be handy in normal projects as well.

When using the operator new, one can provide it with an already allocated memory, so it runs a constructor for a particular type in there. After that, reinterpret that memory as a pointer to your desired object and use it normally. However, deletion is a bit more complicated, as you have to call the destructor on that object manually (because delete must be called on the original memory, not the object).

// using some template type T
auto&& buffer = static_cast<std::byte*>(::operator new(sizeof(T)));
if (!buffer) throw std::bad_alloc();

new (buffer) T();
auto&& object = reinterpret_cast<T*>(buffer);

// ...

object->~T(); // call destructor
delete[] buffer; // properly release memory

I used this trick when implementing a resource manager that needs to hold any user data type (that is still default-constructible in my case): link

Part 4 of 4 in Tuesday Coding Tips

1 Comment

0 votes
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 15 — Mathematical constants in C++

Jakub Neruda - Jun 9
chevron_left
942 Points39 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
23Posts
10Comments
9Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!