You are browsing as a guest. Sign up (or log in) to start making projects!

1h 43m 52s logged

Mini Devlog - How Writing Unit Tests Made Me Fight C++ For An Hour

Whenever I spend some time fighting with C++ instead of actually being productive, I feel like I at least need to get a devlog out of it, so here goes.

Background

I’ve been writing unit tests for my particle simulator, and one thing I’ve noticed is that I have no code to protect global state when a single module is registered more than once, which leads to weird and unintended behavior.

My solution is lazy: silent failure. If a module already exists when addModule(const std::string& name) is called through the module interface function registerModule(const std::string& name) (You can read about why these are separated in an earlier blog post, it’s very cool!), the function just doesn’t register it again. Simple enough, but I wanted to implement it in “correct” C++.

The Implementation (Where Things Went Wrong)

What I did was create a function in module.cpp with internal linkage called getModuleByName which returns a std::optional<Module&>.

Well, apparently for the C++ standard that amounts to heresy, since up until C++26 the committee never managed to agree on how to handle std::optionals that contain references.

Well, I thought, I am already compiling with -std=c++26 in my project, so this should work. But it didn’t. I needed an updated libc++ implementation, which I managed to get through MinGW. I spent 30 more minutes fighting with CMake as it insisted to link against MSVC’s headers, but eventually I did manage to get it to compile.

A normal programmer would have just used std::optional<Module*> but I am definitely not normal.

Was it worth it? probably not. Especially when it’s all for a function which only has internal linkage and is only used in one place. But I like to think that writing code I’m comfortable with will help maintain the codebase in the future.

0
51

Comments 0

No comments yet. Be the first!