Optional Is Not Optional in C++ (and Definitely Not a Pointer)
dev.to·2h·
Discuss: DEV
Flag this post

Last week I had a chat with a few fellow C++ devs, and I was genuinely surprised; some still avoid using std::optional and std::expected. Reason?

This adds extra indirects while access as well as memory allocation.

Basically, there is a belief that they are implemented over pointers. It still pops up more often than you could guess, but it’s simply wrong. Neither std::optional nor std::expected use pointers or heap allocations to store data. Everything lives on the stack - lightweight, fast, and predictable.

Let’s finally put that myth to rest.


The std::optional<T> is just a lightweight wrapper around a value of type T, plus a status flag that tells whether it’s initialized. No heap or pointer usage at all; conceptually, it looks like:

templ...

Similar Posts

Loading similar posts...