Hacker News new | ask | show | jobs
by ensiferum 3549 days ago
I think the example is either naive or then contrived. There's probably some behavioral changes that go with the state of the connection in which case you'd be much better served by having a State interface and then implementations for different actual states.

For example:

class State { ... }; class Connected : public State { ... };

std::unique_ptr<State> state;

2 comments

That has downsides like, for one, requiring allocations for every state transition, and the runtime infrastructure (plus loss of static assurances) required to do downcasts when one needs functionality that only exists on a specific state. For closed state spaces like this example, a discriminated union is far more controlled and has many advantages, whereas subclassing is often better suited to open (or large) sets of states.
It's clearly a contrived example to show how std::variant can be used for a state machine.