Tuesday Coding Tip 16 — Creating objects in existing memory

●5 ●35 ●98
calendar_today • schedule1 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

Want more #programming & #cpp deep dives?

Join 6,122+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 16 of 33 in Tuesday Coding Tips

1 Comment

0 votes

More Posts

Tuesday Coding Tip 33 — Imported CMake targets

Jakub Neruda - Dec 1

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Let's play with C++ reflection

Jakub Neruda - Nov 12

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30
chevron_left
2.2k Points • 138 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
47Posts
40Comments
25Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

3 comments
3 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!