Solving Undefined Behavior in Factories with constinit from C++20 -- Bartlomiej Filipek
A few years ago, I showed an interesting implementation for self-registering classes in factories. It works, but one step might be at the edge of Undefined behavior. Fortunately, with C++20, its new constinit keyword, we can update the code and ensure it’s super safe.
Solving Undefined Behavior in Factories with constinit from C++20
by Bartlomiej Filipek
From the article:
Let’s bring back the topic:
Here’s a typical factory function. It creates
unique_ptrwithZipCompressionorBZCompressionbased on the passed name/filename:
Here are some issues with this approach:
- Each time you write a new class, and you want to include it in the factory, you have to add another if in the
Create()method. Easy to forget in a complex system.- All the types must be known to the factory.
- In
Create(), we arbitrarily used strings to represent types. Such representation is only visible in that single method. What if you’d like to use it somewhere else? Strings might be easily misspelled, especially if you have several places where they are compared.All in all, we get a strong dependency between the factory and the classes.
But what if classes could register themselves? Would that help?


Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
You may have a class that you want to participate in RVO or NRVO, but you also don’t want it to be moved. For example, it may contain a std::mutex, which is not movable. But you nevertheless have to declare a move constructor. What can you do?
Sorting algorithms have been thoroughly studied. Kevlin Henney takes an unexpected paradigm journey into sleep sort.
Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
std::move can allow the efficient transfer of resources from object to to object. Andreas Fertig reminds us that using std::move inappropriately can make code less efficient.
Is it possible to extend a value type in C++? Alf Steinbach describes how to extend enum values.
Registration is now open for CppCon 2023! The conference starts on October 1 and will be held
Registration is now open for CppCon 2023! The conference starts on October 1 and will be held