Most Valuable std::variant (Part 1)

Most std::variant tutorials introduce it as a way to store wildly different types in a single variable – the canonical example being a JSON-like value type that can hold a number, a bool, a string, or a null.

using value_t = std::variant<
    std::monostate,
    int,
    double,
    bool,
    std::string
>;

While this is a valid use case, it has always been my pet peeve to see examples like this one in articles introducing std::variant. They miss what I consider the most important application of std::variant – improving software safety by eliminating invalid program states.

In both cases, we create a new type that is a union of some simpler types. In the previous example, the different alternatives (int, std::string, etc.) are all unrelated values – the variant just holds whichever one was most recently assigned.

In state modelling, the alternatives are operational states – the variant encodes what the program is currently doing and what data is meaningful and useful right now.

Same operation of combining types, but the semantic difference of why we combine the types is what is important.

When RAII gets switched off

RAII – Resource Acquisition Is Initialization – is probably the most important idiom of C++. When an object is constructed, the resource is acquired. When it is destroyed, the resource is released. The destructor does the cleanup, and since the destructor is called automatically whenever the object goes out of scope, the cleanup cannot be forgotten.

We are not going to have classes that need explicitly implemented destructors in this post. But if you do need to do some explicit resource management, mind your rule of N. The destructor is only a part of the story. A class that manages a resource also needs correct copy and move operations, otherwise the resource can still be leaked or released twice. Rainer explained this in detail in C++ Core Guidelines: The Rule of Zero, Five, or Six.

Consider a function that writes some results to a file:

void write_results(const std::string& filename,
                   const std::string& content)
{
    std::ofstream file{filename};
    file << content;

    // 'file' goes out of scope here.
    // Its destructor flushes the buffer and closes
    // the underlying file handle automatically.
    // There is nothing to forget.
}

When the write_results function returns, file goes out of scope, its destructor is called. The destructor flushes the buffer and closes the file handle. There is no need for an explicit file.close() call.

The same principle applies to any resource. Memory managed by std::unique_ptr is freed when it goes out of scope. A mutex locked with std::lock_guard is unlocked when the guard goes out of scope. A database connection wrapped in a custom RAII type is closed when the wrapper is destroyed. RAII is the reason why manual resource management is largely a solved problem in modern C++.

But, what happens when such a resource is not a local variable, but a member of a larger class?

Imagine we are writing a small report-generator application. It has a clear lifecycle:

  1. It starts idle, holding only its output configuration.
  2. It transitions to a running state, opens an output file, and processes a series of items, writing each one to the file.
  3. Finally it completes, at which point the file should be closed and the application should hold a summary of what was done.

The usual approach to model something like this is to start with a class that will contain all the data we will need to implement this simple process:

class application_t {
public:
    explicit application_t(std::string output_path)
        : m_output_path{std::move(output_path)}
    {}

    void start()
    {
        // Let's assume this always succeeds
        m_output_file.open(m_output_path);
        m_running = true;
    }

    void process(const std::string& item)
    {
        if (!m_running) return;
        m_output_file << item << '\n';
        ++m_item_count;
    }

    void stop()
    {
        m_output_file.close(); // easy to forget
        m_running = false;
    }

    std::size_t item_count() const
    {
        return m_item_count;
    }

private:
    std::string   m_output_path;
    std::ofstream m_output_file;      // only meaningful while running
    bool          m_running{false};
    std::size_t   m_item_count{0UZ};  // no meaning before we start
};

The class is small, the code compiles, and the tests pass. So, all is perfect! Right?

The hidden coupling and the invalid state

Look more carefully at the member variables:

std::string   m_output_path;
std::ofstream m_output_file;      // only meaningful while running
bool          m_running{false};
std::size_t   m_item_count{0UZ};  // no meaning before we start

Each of these four members is present in every instance of application_t, during its whole lifetime.

Dead member variables

When the object is first constructed, m_output_file is a default-constructed, closed std::ofstream. It is unused until start() is eventually called. Same with m_item_count.

Similarly, m_output_path and m_output_file are dead weight that will never be used again after stop() is called.

Implicit coupling between members

Another issue is the implicit contract between m_running and m_output_file. For the class to be in a valid state, these two must always agree with each other: if m_running is true, the file must be open; if m_running is false, the file should be closed.

Nothing in the type system enforces this contract. Any member function can change m_running without touching the file, or open the file without setting m_running.

As the class grows, every new member function is one more place where the contract can be accidentally violated. The more member variables we end up putting in the class, the more coupling we will have. And it will not be obvious which variables are coupled, and which are not.

RAII fires too late

There is also the matter of m_output_file.close() in the stop() function. Why do we have RAII, if we still need to manually release resources? RAII has been undermined when we connected the lifetime of the resource to the lifetime of the owning instance of the application_t class. These two lifetimes should not be the same.

A class with too many responsibilities

Step back and look at what application_t is at each point in its lifetime:

  • Before start(): effectively a configuration struct, carrying only m_output_path.
  • Between start() and stop(): an active file writer, managing an open stream and a running count.
  • After stop(): a result summary, holding only m_item_count.

These are three different roles, each with its own data and its own invariants. The single-responsibility principle says that a class should have one reason to change – but this class has (at least) three. Lumping these three roles into a single class means that every role must carry the dead weight of the other two. The transitions between the roles are maintained only by programmer discipline, not by anything the language can check.

Splitting the class into states

The fix starts with recognising that application_t is not really a single thing. It is three things that happen to share a name. The correct representation is three separate types, one per state, each containing only the data relevant to that state:

struct idle_t {
    std::string output_path;
};

struct running_t {
    explicit running_t(const std::string& path)
        : file{path}
    {}

    std::ofstream file;
    std::size_t item_count{0UZ};
};

struct done_t {
    std::size_t item_count;
};

With those types in hand, application_t becomes a simple alias:

using application_t = std::variant<
    idle_t,
    running_t,
    done_t
>;

An application_t object is always in exactly one of the three states. There is no fourth possibility (apart from the valueless_by_exception, but this is not a situation we can be in in this case), no combination of flags and half-open files that the program has to guard against.

What we gain

Automatic disposal when leaving a state

Look at the stop() function which changes the program state from running_t to done_t:

void stop(application_t& app)
{
    if (auto* s = std::get_if<running_t>(&app)) {
        auto count = s->item_count;
        app = done_t{count};
    }
}

When we assign done_t{count} to app, the std::variant destroys the value it currently holds – and replaces it with the new value. Destroying the running_t calls the destructor of its std::ofstream member, which flushes the buffer and closes the file.

We did not call file.close() explicitly. Closing the file is no longer something we have to do – it is a consequence of leaving the running state. RAII is restored.

The same reasoning applies to any resource. Whatever a state holds – heap memory, a mutex lock, a network socket – is released automatically when the program transitions away from that state, regardless of how the transition happens.

No implicit coupling between members

In the original application_t, m_running and m_output_file had to be kept in sync by hand. In the variant design, this question does not arise. If the current state is running_t, the file is open – it was opened in the constructor, and it will be closed when that state is left. There is no separate boolean flag to get out of sync with anything. Each state type contains exactly the members it needs, and nothing else.

These state types can also grow, which can lead to new couplings getting introduced. But separating coupled from uncoupled member variables will still be easier as the state types are still significantly smaller than what they would have been if all are bunched together in a single class.

Invariants are maintained by construction

With the flat class it was possible to have an instance where m_running was true but the file was closed, or where the file was open long after processing had stopped. Nothing in the type system prevented it.

With the variant, these invalid combinations cannot be represented at all. A running_t always has an open file (assuming construction succeeded). A done_t has no file member, open or otherwise. The type system, rather than programmer discipline, enforces the invariants.

What is coming in the next parts

We have seen how modeling program state using std::variant restores RAII, reduces or even eliminates implicit coupling between members, and makes invalid program states impossible to represent.

The transition functions like stop() above use std::get_if to inspect the active state and assign a new state directly. This works for small examples, but it does not scale well when many states are involved and transitions need to handle the current state in a generic manner.

In the next part, we will look at std::visit together with the overloaded pattern, which lets us write a single expression that handles every possible state cleanly. We will also see how to write transition functions that can prevent accidentally accessing a state that has already been transitioned away from to make the programs even more safe and robust.


Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, Honey Sukesan, bruce_lee_wayne, Silviu Ardelean, schnapper79, Seeker, and Sundareswaran Senthilvel.

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

My special thanks to Embarcadero
My special thanks to PVS-Studio
My special thanks to Tipi.build 
My special thanks to Take Up Code
My special thanks to SHAVEDYAKS

Modernes C++ GmbH

Modernes C++ Mentoring (English)

Do you want to stay informed about the mentoring programs? Subscribe Here

Beatrix Jaud-Grimm
Kelterstraße 23
72108 Rottenburg

Mobil: +49 15561 737372
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org