Solving Undefined Behavior in Factories with constinit from C++20 -- Bartlomiej Filipek

ub_constinit.pngA 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_ptr with ZipCompression or BZCompression based 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?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.