C++ Programming: Know Your Goal

Sean Hoffman
4 min readMay 13, 2023

There are a lot of wonderful features in recent implementations of C++ (and by “recent” I mean C++11 onward), but it is my belief that you should generally be selective about which ingredients are tossed into the soup, and that’s with any language.

I stumbled upon a Reddit discussion of using std::optional<> vs allocating a raw pointer. One reasonable perspective was that using std::optional over simply using a raw pointer was safer and could avoid a dynamic allocation, which should in theory be faster than allocating and checking for a pointer. The other perspective was that using a raw pointer, as much as it’s frowned upon in modern C++, was simpler and potentially faster, and that std::optional really didn’t provide any benefit other than avoiding a raw pointer.

Some code was posted, and to my surprise, returning and using a raw pointer was more than 2x as fast. I thought it would be closer. I mean, I can give up 20 percent performance for safety. But twice as fast!? Now is it as safe as using optional<>? Unless you wrap it in a smart pointer, then the answer is no. Having had to debug many memory leaks in services and drivers before, I can tell you it’s no fun tracking them down, so safety is a concern.

But running twice as slow is also a concern. As a polyglot I understand that the only reason C++ has any reason to be right now is performance. The Rust folks are pounding at the door with both portions of both the Windows and Linux kernel now being written in Rust. And Go gets you to anywhere between…

--

--

Sean Hoffman

Software Developer (C++, C#, Go, others), Husband, Father. I eat fried potatoes annually on July 14th.