State
What you will learn on this page
Section titled “What you will learn on this page”- The problem State solves, shown before the pattern is named: an object whose allowed operations and data depend on its stage in a lifecycle.
- How to decide which data members belong to the whole object and which belong to one stage.
- The parts of the pattern: the context, the state interface, and one concrete state per stage.
- A safe C++ way to change state: each event returns the next state, and the context replaces the old one afterwards.
- A second C++ form,
std::variant, and how to choose between it, state objects, and a plainenumwith aswitch.
The problem
Section titled “The problem”A company keeps its staff guides in a small publishing tool. A guide goes through review before anyone can read it.
Requirements:
- FR-1 A new document is a draft. Only a draft can be edited.
- FR-2 The author submits a draft for review. An empty document cannot be submitted.
- FR-3 In review, reviewers approve it. The author cannot approve their own document, and nobody can approve twice in the same review. With two approvals, the document is published, and its version number goes up by one.
- FR-4 A reviewer can reject it with a reason. It goes back to draft, and the author sees the reason until they submit again. The next review starts from zero approvals.
- FR-5 A published document can be revised (back to draft, same version) or archived. A draft can also be archived. An archived document allows nothing.
- FR-6 Any event not allowed in the current stage is refused with an error that names the event and the stage.
Text description of the diagram
A document is created as a draft. Editing a draft keeps it a draft. Submitting a draft whose content is not empty moves it to in review. In review, an approval that leaves fewer than 2 approvals keeps it in review; the second approval moves it to published and adds one to the version. Rejecting it in review moves it back to draft and keeps the reason. Revising a published document moves it to draft. Archiving moves a draft or a published document to archived, which is final. Any event not shown for a stage is refused.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> Draft : create
Draft --> Draft : edit
Draft --> InReview : submit [content not empty]
InReview --> InReview : approve [fewer than 2 approvals]
InReview --> Published : approve [second approval] / version + 1
InReview --> Draft : reject / keep the reason
Published --> Draft : revise
Draft --> Archived : archive
Published --> Archived : archive
Archived --> [*]The same rules as a table: every stage against every event. A blank cell would be a rule nobody decided, so every cell is filled.
| Event | Draft | In review | Published | Archived |
|---|---|---|---|---|
| edit | change the content | refuse | refuse | refuse |
| submit | → in review, if not empty | refuse | refuse | refuse |
| approve | refuse | record; the second → published, version + 1 | refuse | refuse |
| reject | refuse | → draft, with the reason | refuse | refuse |
| revise | refuse | refuse | → draft | refuse |
| archive | → archived | refuse | → archived | refuse |
“Refuse” in the table means the FR-6 error. Three other errors are not about the stage at all, and they apply even where the event is allowed: an author approving or rejecting their own document, a reviewer approving twice, and submitting an empty document. Those are checks on the arguments or the content, made inside the stage that allows the event.
Where State shows up in requirements. Listen for “only a draft
can…”, “after it is published, it cannot…”, “while it is in
review…”, “it goes back to…”. Each ties what is allowed to a stage
in a lifecycle. In code, the signal is the same switch (status_), or
if (status_ == …), at the top of most member functions, and data
members whose comments say “meaningful only while…”. State is one of
the patterns that comes up most often, but most objects with a status
are well served by the enum and switch that
the state diagram page teaches; the
pattern is for when the stages grow their own data and behaviour.
The straightforward solution
Section titled “The straightforward solution”The first version stores the stage in an enum class and checks it in
every event:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The four stages of review, as plain names with no data of their own.enum class Status { draft, in_review, published, archived };
// The first design: one class holds the stage as an enum, and every event// checks it (with an if or a switch) before acting. Refused events throw// std::logic_error ("cannot approve while draft"). `final`: no class may// derive from this one.class Document final {public: // Throws std::invalid_argument if the title or author is empty. Document(std::string title, std::string author, std::string content);
void edit(std::string content); void submit(); void approve(const std::string& reviewer); void reject(const std::string& reviewer, std::string reason); void revise(); void archive();
std::string describe() const; int version() const { return data_.version; }
private: DocumentData data_; Status status_ = Status::draft; // every document starts as a draft // The weak spot: these two members exist in EVERY stage, so each // transition must remember to reset the one that stops applying. std::set<std::string> approved_by_; // meaningful only while in_review std::string feedback_; // meaningful only while draft};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Records one reviewer's approval, and publishes the document once// required_approvals (2) different reviewers have approved. Only allowed// in review. Throws std::invalid_argument if the reviewer is the author or// has already approved; refuse() throws std::logic_error in other stages.void Document::approve(const std::string& reviewer) { // A switch with one case per Status and no `default`, so the compiler // (with -Wswitch) warns here if a new Status is added and forgotten. switch (status_) { case Status::in_review: if (reviewer == data_.author) { throw std::invalid_argument{"authors cannot approve their own document"}; } // insert returns a pair: an iterator to the element, and a bool // that is true only if the name was not already in the set. So // `.second` false means "this reviewer already approved". The // set counts approvals from earlier reviews too, because // nothing ever empties it (see reject below). if (!approved_by_.insert(reviewer).second) { throw std::invalid_argument{reviewer + " already approved"}; } if (approved_by_.size() >= required_approvals) { ++data_.version; status_ = Status::published; } return; // Three case labels in a row share one body. refuse() always throws // (it is marked [[noreturn]]), so control never falls off the end. case Status::draft: case Status::published: case Status::archived: refuse("approve", status_); }}
// Sends the document back to draft with the reviewer's reason. Only// allowed in review, and not by the author.void Document::reject(const std::string& reviewer, std::string reason) { switch (status_) { case Status::in_review: if (reviewer == data_.author) { throw std::invalid_argument{"authors cannot reject their own document"}; } feedback_ = std::move(reason); // THE BUG: approved_by_ is left as it is, so the next review // starts with this review's approvals already counted. status_ = Status::draft; // approved_by_ is not cleared return; case Status::draft: case Status::published: case Status::archived: refuse("reject", status_); }}It works for most of the story, and it is easy to read. But look at the
two data members at the bottom of the class. approved_by_ means
something only in review, and feedback_ only in a draft. They exist
in every stage, so every transition must remember to reset the ones
that no longer apply. submit clears feedback_. Nothing clears
approved_by_, as the comment in reject admits. This test pins the
result:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) fails,// and prints both values, unless they are equal. Both come from the site's// small test header, lld_test.hpp.// Pins the bug in the enum + switch version: approvals from a rejected// review are still counted in the next one.LLD_TEST(before_a_rejected_review_leaks_its_approvals) { before::Document doc{"Guide", "Ana", "Hello."}; doc.submit(); doc.approve("Ben"); doc.reject("Chen", "too short"); doc.edit("Hello, and welcome."); doc.submit(); // A brand-new review, yet Ben's approval from the rejected one counts. LLD_CHECK_EQ(doc.describe(), std::string{"in review (1 of 2 approvals)"}); doc.approve("Chen"); // one approval in this review... LLD_CHECK_EQ(doc.describe(), std::string{"published"}); // ...and it is published}After a rejection, the next review starts with Ben’s old approval already counted, so one new approval publishes the document. That breaks FR-3 and FR-4.
The one-line fix is to clear approved_by_ in reject. But the real
cause is that the class allows impossible states: “a draft with
approvals”, “a published document with feedback”. The type lets them
exist, and only the discipline of every function stops them. Each new
stage or new piece of stage data adds more combinations to get wrong.
Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”For each data member, ask: in which stages does it mean something?
| Data member | Meaningful in | So it belongs to |
|---|---|---|
| title, author | every stage | the document |
| content | every stage (edited in draft only) | the document |
| version | every stage | the document |
| approvals so far | in review only | the in-review stage |
| rejection reason | draft only | the draft stage |
Then, for each event, ask: whose rules decide it?
| Function | Its rules depend on | So it belongs to |
|---|---|---|
edit, submit |
being a draft | the draft stage |
approve, reject |
being in review | the in-review stage |
revise |
being published | the published stage |
archive |
draft or published | those two stages |
| “refuse with a message” | nothing | written once, as the default for every stage |
| holding the current stage | nothing | the document |
The data and the rules of each stage go together. When a stage ends, its data should end with it. That is what the pattern arranges.
The pattern
Section titled “The pattern”That is the State pattern.
| Role | What it does | In this example |
|---|---|---|
| Context | The object callers use; holds the shared data and the current state | Document |
| State interface | One function per event; the default refuses | DocumentState |
| Concrete states | One per stage; allow their events and hold their own data | Draft, InReview, Published, Archived |
class Document final
the context
Data members
DocumentData data_;title, author, content, versionstd::unique_ptr<DocumentState> state_;never nullvoid move_to(std::unique_ptr<DocumentState> next);private; stays if null
Member functions
void submit();and edit, approve, reject, revise, archivestd::string describe() const;
interface (abstract class) DocumentState
Member functions
virtual std::string_view name() const = 0;virtual std::unique_ptr<DocumentState> approve(DocumentData& doc, const std::string& reviewer);default: refusevirtual std::unique_ptr<DocumentState> submit(DocumentData& doc);default: refuse; and one per event
class Draft final
a DocumentState
Data members
std::string feedback_;why it was sent back
Member functions
std::unique_ptr<DocumentState> submit(DocumentData& doc) override;and edit, archive
class InReview final
a DocumentState
Data members
std::set<std::string> approved_by_;starts empty in every review
Member functions
std::unique_ptr<DocumentState> approve(DocumentData& doc, const std::string& reviewer) override;and reject
class Published final
a DocumentState
Member functions
std::unique_ptr<DocumentState> revise(DocumentData& doc) override;and archive
class Archived final
a DocumentState
Member functions
std::string_view name() const override;every event refused by default
Text description of the diagram
A solid arrow means “owns”, a dashed arrow means “uses”, and a thick arrow means “implements”. Document owns DocumentData (title, author, content, version) and owns one DocumentState. Draft (holding the feedback), InReview (holding approved_by), Published, and Archived each implement DocumentState. DocumentState has a dashed arrow to DocumentData labelled “reads and updates, per event”.
Diagram source (Mermaid)
flowchart TB
DOC["Document"] -->|owns| DD["DocumentData<br/>title, author, content, version"]
DOC -->|owns one| ST["DocumentState<br/>interface"]
DR["Draft<br/>feedback"] ==>|implements| ST
IR["InReview<br/>approved_by"] ==>|implements| ST
PB["Published"] ==>|implements| ST
AR["Archived"] ==>|implements| ST
ST -.->|"reads and updates, per event"| DDThe C++ implementation
Section titled “The C++ implementation”The shared data
Section titled “The shared data”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What every document has, whatever stage of review it is in.struct DocumentData { std::string title; std::string author; std::string content; int version = 0; // goes up by one each time the document is published};
// How many different reviewers must approve before a document is// published. `inline constexpr` makes it one compile-time constant that// every file including this header shares.inline constexpr std::size_t required_approvals = 2;The state interface: refuse by default
Section titled “The state interface: refuse by default”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One stage of a document's review. Each event returns the next state,// or nullptr to stay in this one. By default an event is refused; each// state overrides only the events it allows.// Every event takes the shared DocumentData by reference (the state reads// and changes it during the call, but keeps no pointer to it) and returns// a std::unique_ptr: ownership of a brand-new state object, handed to the// caller, or an empty pointer for "no change of stage".class DocumentState {public: // virtual, so that destroying a state through a DocumentState pointer // (as std::unique_ptr<DocumentState> does) runs the real state's // destructor and frees its data, such as InReview's approvals. virtual ~DocumentState() = default;
// `= 0` makes name() pure virtual: every concrete state must say what // it is called. describe() has a default (just the name), which states // with extra data override. virtual std::string_view name() const = 0; virtual std::string describe() const { return std::string{name()}; }
virtual std::unique_ptr<DocumentState> edit(DocumentData& doc, std::string content); virtual std::unique_ptr<DocumentState> submit(DocumentData& doc); virtual std::unique_ptr<DocumentState> approve(DocumentData& doc, const std::string& reviewer); virtual std::unique_ptr<DocumentState> reject(DocumentData& doc, const std::string& reviewer, std::string reason); virtual std::unique_ptr<DocumentState> revise(DocumentData& doc); virtual std::unique_ptr<DocumentState> archive(DocumentData& doc);
protected: // protected: only derived states may construct or copy the base part. // Outside code cannot assign one DocumentState& to another, which would // copy only the base part (slicing). DocumentState() = default; DocumentState(const DocumentState&) = default; DocumentState& operator=(const DocumentState&) = default;
// Throws std::logic_error: "cannot <event> while <name>". // [[noreturn]] tells the compiler it never returns normally (it always // throws), so a function that ends by calling it needs no return. [[noreturn]] void refuse(std::string_view event) const;};Three decisions are in this interface:
- Each event returns the next state, or
nullptrto stay. The state decides where to go; the document does the moving. Why that matters is explained in the next section. - The events are virtual but not pure. The default refuses the
event, so each state overrides only what it allows.
Archivedoverrides nothing but its name. FR-6’s message is written once:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The default for every event: refuse it. The parameters have no names// because the defaults never use them (that also avoids "unused parameter"// warnings). There is no return statement: refuse() always throws.std::unique_ptr<DocumentState> DocumentState::edit(DocumentData&, std::string) { refuse("edit");}std::unique_ptr<DocumentState> DocumentState::submit(DocumentData&) { refuse("submit");}std::unique_ptr<DocumentState> DocumentState::approve(DocumentData&, const std::string&) { refuse("approve");}std::unique_ptr<DocumentState> DocumentState::reject(DocumentData&, const std::string&, std::string) { refuse("reject");}std::unique_ptr<DocumentState> DocumentState::revise(DocumentData&) { refuse("revise");}std::unique_ptr<DocumentState> DocumentState::archive(DocumentData&) { refuse("archive");}
// name() is virtual, so it gives the real state's name, for example// "cannot edit while in review". std::string{...} turns each string_view// into a std::string so they can be joined with +.void DocumentState::refuse(std::string_view event) const { throw std::logic_error{"cannot " + std::string{event} + " while " + std::string{name()}};}- Each event receives the shared data as a parameter, a
DocumentData&, instead of each state storing a pointer to the document. A state then cannot outlive or dangle from the document it serves, and it can be tested with a plainDocumentData.
The states
Section titled “The states”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The four concrete states. Each is `final` (nothing derives from it),// overrides only the events that stage allows, and holds only its own// data. `override` asks the compiler to check that each function really// replaces a virtual function of DocumentState.
// Being written. Allows edit, submit, and archive. A draft that a reviewer// sent back carries the reason; a new one has none.class Draft final : public DocumentState {public: // `= {}` makes the feedback optional: Draft{} has an empty reason. // explicit: a string never silently becomes a Draft. explicit Draft(std::string feedback = {}) : feedback_{std::move(feedback)} {}
std::string_view name() const override { return "draft"; } std::string describe() const override;
std::unique_ptr<DocumentState> edit(DocumentData& doc, std::string content) override; std::unique_ptr<DocumentState> submit(DocumentData& doc) override; std::unique_ptr<DocumentState> archive(DocumentData& doc) override;
private: std::string feedback_; // why a reviewer sent it back; empty if none};
// Waiting for approvals. Allows approve and reject. Its approvals live and// die with this object, so each review starts with none.class InReview final : public DocumentState {public: std::string_view name() const override { return "in review"; } std::string describe() const override;
std::unique_ptr<DocumentState> approve(DocumentData& doc, const std::string& reviewer) override; std::unique_ptr<DocumentState> reject(DocumentData& doc, const std::string& reviewer, std::string reason) override;
private: std::set<std::string> approved_by_; // starts empty in every review};
// Live. Allows revise (back to a new draft) and archive.class Published final : public DocumentState {public: std::string_view name() const override { return "published"; }
std::unique_ptr<DocumentState> revise(DocumentData& doc) override; std::unique_ptr<DocumentState> archive(DocumentData& doc) override;};
// Finished. Allows nothing.class Archived final : public DocumentState {public: std::string_view name() const override { return "archived"; } // Every event is refused: the defaults do that.};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// "draft", or "draft (returned: <reason>)" if a reviewer sent it back.std::string Draft::describe() const { return feedback_.empty() ? "draft" : "draft (returned: " + feedback_ + ")";}
// Editing changes the shared data, not the stage. `content` was passed by// value, so it is moved into the document instead of copied again.std::unique_ptr<DocumentState> Draft::edit(DocumentData& doc, std::string content) { doc.content = std::move(content); return nullptr; // still a draft}
// Moves to review, unless there is nothing to review. The unique_ptr to an// InReview converts to a unique_ptr to its base, DocumentState. This Draft// (and its feedback) is destroyed later, when the Document replaces it.std::unique_ptr<DocumentState> Draft::submit(DocumentData& doc) { if (doc.content.empty()) { throw std::logic_error{"cannot submit an empty document"}; } return std::make_unique<InReview>(); // a fresh review: no approvals yet}
// The data is not needed, so the parameter has no name.std::unique_ptr<DocumentState> Draft::archive(DocumentData&) { return std::make_unique<Archived>();}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::string InReview::describe() const { return "in review (" + std::to_string(approved_by_.size()) + " of " + std::to_string(required_approvals) + " approvals)";}
// Adds one approval, or, if it is the last one needed, moves to Published// and raises the version. Throws std::invalid_argument for the author or a// repeat reviewer. Every check comes before any change, so a refused// approval changes nothing.std::unique_ptr<DocumentState> InReview::approve(DocumentData& doc, const std::string& reviewer) { if (reviewer == doc.author) { throw std::invalid_argument{"authors cannot approve their own document"}; } if (approved_by_.contains(reviewer)) { // contains (C++20): is the name in the set? throw std::invalid_argument{reviewer + " already approved"}; } // "Counting this one, are we still short?" With 2 required: the first // approval gives 0 + 1 < 2, so stay; the second gives 1 + 1 < 2, false. if (approved_by_.size() + 1 < required_approvals) { approved_by_.insert(reviewer); return nullptr; // still in review } // The last approval: this state is about to be replaced, so the name // is not recorded. Allocate first: if it throws, nothing has changed. auto next = std::make_unique<Published>(); ++doc.version; return next;}
// Back to a draft that carries the reason. The approvals are not copied// anywhere: they are destroyed with this InReview when the Document moves on.std::unique_ptr<DocumentState> InReview::reject(DocumentData& doc, const std::string& reviewer, std::string reason) { if (reviewer == doc.author) { throw std::invalid_argument{"authors cannot reject their own document"}; } return std::make_unique<Draft>(std::move(reason));}How this code works: InReview::approve
approve either refuses, stays in review, or hands back a new state.
- Refusals first. If the reviewer is the author, or their name is
already in
approved_by_, it throwsstd::invalid_argument. Nothing has been changed yet, so a refused approval leaves the document as it was. - Still short?
approved_by_.size() + 1 < required_approvalsasks whether, counting this approval, the review is still short of 2. If so, the name is recorded and the function returnsnullptr, which the document reads as “stay in this state”. - The last approval. Otherwise this approval completes the review.
std::make_unique<Published>()creates the next state first; only then isdoc.versionraised. If the allocation threw, the version would be unchanged. The new state is returned, and the document destroys thisInReviewafterapprovehas returned.
With Ana as the author, in one review:
| Call | approved_by_ before |
Check | Result |
|---|---|---|---|
approve("Ana") |
empty | the author | throws std::invalid_argument |
approve("Ben") |
empty | 0 + 1 < 2 is true | records Ben, returns nullptr |
approve("Ben") |
Ben | already approved | throws std::invalid_argument |
approve("Chen") |
Ben | 1 + 1 < 2 is false | version 0 to 1, returns a Published state |
reject is shorter: after the author check, it returns a new Draft
holding the reason. The approvals are never copied into it.
The bug from the first version cannot happen here. submit creates a
new InReview, and a new InReview has no approvals. reject
creates a new Draft with the reason, and the InReview that held the
approvals is destroyed when the document moves on. No function has to
remember to reset anything.
approve changes nothing until every check has passed, and on the
last approval it creates the Published state before it raises the
version. If std::make_unique threw std::bad_alloc, the document
would be exactly as it was: in review, with the same approvals and the
same version, so the reviewer can simply try again. (The last
reviewer’s name is not recorded, because the InReview that would hold
it is about to be destroyed.)
The context
Section titled “The context”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The document readers and reviewers use. It forwards every event to its// current state and moves to the state the event returns.// It owns the shared data by value, and the current state through a// std::unique_ptr, so the state is freed automatically when replaced.class Document final {public: // Starts as a Draft. Throws std::invalid_argument if the title or the // author is empty. Document(std::string title, std::string author, std::string content);
// Each event throws whatever the current state throws: std::logic_error // if the stage does not allow it (or, for submit, if the content is // empty), std::invalid_argument for a bad reviewer.
void edit(std::string content); void submit(); void approve(const std::string& reviewer); void reject(const std::string& reviewer, std::string reason); void revise(); void archive();
// Every name() returns a string literal, which lives for the whole // program, so this view stays valid even after the state changes. std::string_view status() const { return state_->name(); } std::string describe() const { return state_->describe(); } int version() const { return data_.version; } const DocumentData& data() const { return data_; }
private: void move_to(std::unique_ptr<DocumentState> next); // stays put if null
DocumentData data_; // Never null while the document is in use. (A moved-from Document has // a null state_; it may only be destroyed or assigned to.) std::unique_ptr<DocumentState> state_; // never null};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Members are built in the order they are declared: data_, then state_.// If the check below throws, both are destroyed again, so nothing leaks.Document::Document(std::string title, std::string author, std::string content) : data_{std::move(title), std::move(author), std::move(content)}, state_{std::make_unique<Draft>()} { if (data_.title.empty() || data_.author.empty()) { throw std::invalid_argument{"a document needs a title and an author"}; }}
// Every event has the same shape. state_->edit(...) is a virtual call, so// it runs the CURRENT state's version (Draft::edit, or the refusing// default). Its result goes to move_to. If the state throws, move_to is// never reached, and the document keeps its state.void Document::edit(std::string content) { move_to(state_->edit(data_, std::move(content))); }void Document::submit() { move_to(state_->submit(data_)); }void Document::approve(const std::string& reviewer) { move_to(state_->approve(data_, reviewer));}void Document::reject(const std::string& reviewer, std::string reason) { move_to(state_->reject(data_, reviewer, std::move(reason)));}void Document::revise() { move_to(state_->revise(data_)); }void Document::archive() { move_to(state_->archive(data_)); }
// The state's function has already returned, so replacing (and so// destroying) the old state here is safe.// `next` arrives by value: this function now owns the new state. An empty// pointer means "stay". Otherwise, assigning to state_ deletes the old// state and takes ownership of the new one.void Document::move_to(std::unique_ptr<DocumentState> next) { if (next) { state_ = std::move(next); }}Every event is one line: ask the current state, then move to what it
returns. The document has no switch and no knowledge of which stage
allows what.
Who changes the state, and when
Section titled “Who changes the state, and when”Many descriptions of this pattern let a state change the context’s
state itself: the state calls something like doc.set_state(...). In
C++, with the context owning its state through a std::unique_ptr,
that is a trap.
Returning the next state avoids the problem by construction. The state’s
function finishes, returns, and only then does Document::move_to
replace (and destroy) the old state. If a design really needs the state
to call back into the context, the rule is that the call that replaces
the state must be the last thing the function does. Returning the
next state makes that rule unnecessary.
Ownership and lifetime
Section titled “Ownership and lifetime”| Object | Owner | Lives |
|---|---|---|
DocumentData |
the Document, by value |
as long as the document |
| The current state | the Document, through std::unique_ptr |
from the transition into it until the transition out |
| A state’s own data | that state | exactly as long as the stage: approvals die with the review |
| The next state | the event’s return value, then the Document |
moved into state_ by move_to |
Because Document holds a std::unique_ptr, it can be moved but
not copied. If documents had to be copied, each state would need a
clone() function, or the std::variant form below, which copies for
free. A moved-from Document has a null state_, so its events must
not be called; the only safe things to do with it are to destroy it or
assign a new document to it. The variant form has no such hole.
DocumentState keeps its copy operations protected. Because it is
abstract, nobody can copy one by value anyway; what protected blocks
is assignment through base references, where a = b on two
DocumentState& would copy only the base part and leave the rest of
a as it was (a form of slicing).
One approval, step by step
Section titled “One approval, step by step”Text description of the diagram
The caller calls approve(“Chen”) on the Document. The Document calls approve on its InReview state, passing its data and “Chen”. InReview checks that Chen is not the author and has not already approved. Because this is the second approval, it creates a Published state, then adds one to the version in the data, and returns the Published state to the Document. The Document’s move_to replaces its state with the Published state, which destroys the InReview state. Then approve returns to the caller.
Diagram source (Mermaid)
sequenceDiagram
participant C as caller
participant D as Document
participant R as InReview state
participant P as Published state
C->>D: approve("Chen")
D->>R: approve(data_, "Chen")
R->>R: check author and repeat
R->>P: make_unique (second approval)
R->>R: version + 1 in data_
R-->>D: the Published state
D->>D: move_to: state_ = Published, InReview destroyed
D-->>C: returnsThe same review story runs against all three designs. It is a function template, so it works with any type that has the same member functions:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One review story, run against any of the three Document designs. Each// line is the event and then the document's version and status, or why// the event was refused.// `template <class Doc>`: Doc is a placeholder for a type, filled in by the// caller, as in review_story<Document>(). The code only needs Doc to have// these member functions; the three designs share no base class.template <class Doc>std::vector<std::string> review_story() { Doc doc{"Onboarding guide", "Ana", "Welcome to the team."}; // Ana is the author std::vector<std::string> log; // A helper lambda that runs one event and logs the result. [&] lets it // use `doc` and `log` by reference. `auto action` makes it a generic // lambda: each call can pass a different little lambda as the action. auto step = [&](const std::string& event, auto action) { try { action(); // run the event; if it throws, skip straight to catch log.push_back(event + ": v" + std::to_string(doc.version()) + " " + doc.describe()); // std::invalid_argument is a kind of std::logic_error, so this also // catches "Ben already approved" and "authors cannot approve ...". // Any other exception is not caught here. } catch (const std::logic_error& refused) { log.push_back(event + ": refused: " + refused.what()); } }; // Each action is a lambda; [&] lets it call doc. "start" does nothing, // so its line just shows the starting state. step("start", [] {}); step("submit", [&] { doc.submit(); }); step("approve by Ben", [&] { doc.approve("Ben"); }); step("reject by Chen", [&] { doc.reject("Chen", "add the Wi-Fi steps"); }); step("approve by Ben", [&] { doc.approve("Ben"); }); // refused: it is a draft now step("edit", [&] { doc.edit("Welcome to the team. Wi-Fi: ask the front desk."); }); step("submit", [&] { doc.submit(); }); // a new review step("approve by Ben", [&] { doc.approve("Ben"); }); // must count again step("approve by Chen", [&] { doc.approve("Chen"); }); // second approval: published step("edit", [&] { doc.edit("Welcome!"); }); step("revise", [&] { doc.revise(); }); step("archive", [&] { doc.archive(); }); step("submit", [&] { doc.submit(); }); // refused: archived allows nothing return log;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Run the same story three times, once per design, by naming the type// in the angle brackets. Print the state-object version in full.const std::vector<std::string> with_objects = review_story<Document>();for (const std::string& line : with_objects) { std::cout << line << '\n';}
// == on two vectors is true only if they have the same length and every// line matches.const std::vector<std::string> with_variant = review_story<var::Document>();std::cout << "variant form agrees: " << (with_variant == with_objects ? "yes" : "no") << '\n';
const std::vector<std::string> with_switch = review_story<before::Document>();std::cout << "enum + switch version differs:\n";// Print only the lines where the enum + switch log differs. The loop// stops at the end of the shorter log, so neither is read past its end;// i + 1 turns the 0-based index into a step number counted from 1.for (std::size_t i = 0; i < with_objects.size() && i < with_switch.size(); ++i) { if (with_switch[i] != with_objects[i]) { std::cout << " step " << i + 1 << ": " << with_switch[i] << '\n'; }}How this code works: review_story and main
- One story, three types.
review_storyis a function template.review_story<Document>()has the compiler write a version of it withDocreplaced byDocument;review_story<var::Document>()andreview_story<before::Document>()produce two more. Each copy builds its own document, with Ana as the author. stepruns one event. It is a lambda that takes the event’s label and anaction, another lambda that calls one member function ondoc. It callsaction()insidetry. If the action returns,steplogs the label, the version, anddescribe(), as inapprove by Ben: v0 in review (1 of 2 approvals). If the action throws astd::logic_error, orstd::invalid_argument, which is a kind oflogic_error,steplogsrefused:and the message instead, and the story goes on to the next step.- The story’s 13 steps include three that must be refused: approving a draft (step 5), editing a published document (step 10), and submitting an archived one (step 13).
maincompares the logs. It prints the state-object log, then compares the variant log with it using==, which is true only if every line matches. Last, it prints each line of theenumandswitchlog that differs, numbered from 1.
The two differences are steps 7 and 8. At step 7 the old design starts
the new review with Ben’s approval from step 3 still in approved_by_,
so it shows 1 of 2 approvals. At step 8, inserting Ben again fails, so
it throws Ben already approved. At step 9, Chen’s approval is the second
in the set either way, so both designs publish and the logs agree again.
start: v0 draftsubmit: v0 in review (0 of 2 approvals)approve by Ben: v0 in review (1 of 2 approvals)reject by Chen: v0 draft (returned: add the Wi-Fi steps)approve by Ben: refused: cannot approve while draftedit: v0 draft (returned: add the Wi-Fi steps)submit: v0 in review (0 of 2 approvals)approve by Ben: v0 in review (1 of 2 approvals)approve by Chen: v1 publishededit: refused: cannot edit while publishedrevise: v1 draftarchive: v1 archivedsubmit: refused: cannot submit while archivedvariant form agrees: yesenum + switch version differs: step 7: submit: v0 in review (1 of 2 approvals) step 8: approve by Ben: refused: Ben already approvedThe first 13 lines are the state-object design. The enum and
switch version differs in exactly two steps, both caused by the leaked
approval: after resubmitting, it already shows one approval (step 7),
and it then refuses Ben as having “already approved” (step 8).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_CHECK(condition) fails if the condition is false. LLD_CHECK_THROWS(// expression, type) fails unless the expression throws that type.//// Walks one document through every stage and tries the events that stage// does not allow: each must throw std::logic_error.LLD_TEST(each_state_refuses_the_events_it_does_not_allow) { Document doc{"Guide", "Ana", "Hello."}; LLD_CHECK_THROWS(doc.approve("Ben"), std::logic_error); // draft LLD_CHECK_THROWS(doc.revise(), std::logic_error); doc.submit(); LLD_CHECK_THROWS(doc.edit("x"), std::logic_error); // in review LLD_CHECK_THROWS(doc.submit(), std::logic_error); LLD_CHECK_THROWS(doc.archive(), std::logic_error); doc.approve("Ben"); doc.approve("Chen"); LLD_CHECK_EQ(doc.status(), std::string_view{"published"}); LLD_CHECK_THROWS(doc.edit("x"), std::logic_error); LLD_CHECK_THROWS(doc.reject("Ben", "late"), std::logic_error); doc.archive(); // A list of four events to try on the archived document. Each lambda // captures nothing, and the `+` in front turns it into a plain function // pointer, void(*)(Document&). That gives all four the same type, which // a brace list needs (four lambdas would be four different types). for (auto event : {+[](Document& d) { d.edit("x"); }, +[](Document& d) { d.submit(); }, +[](Document& d) { d.revise(); }, +[](Document& d) { d.archive(); }}) { LLD_CHECK_THROWS(event(doc), std::logic_error); // archived refuses everything }}
// in_review() (a helper at the top of this file) returns a new document// that has just been submitted. The author, Ana, cannot approve; Ben// cannot approve twice; only Chen's approval, the second, publishes.LLD_TEST(a_review_needs_two_different_reviewers_other_than_the_author) { Document doc = in_review(); LLD_CHECK_THROWS(doc.approve("Ana"), std::invalid_argument); doc.approve("Ben"); LLD_CHECK_THROWS(doc.approve("Ben"), std::invalid_argument); LLD_CHECK_EQ(doc.status(), std::string_view{"in review"}); doc.approve("Chen"); LLD_CHECK_EQ(doc.status(), std::string_view{"published"}); LLD_CHECK_EQ(doc.version(), 1);}
// The fix for the before-version bug, checked: after a rejection, the next// review starts at 0 approvals, and Ben may approve again.LLD_TEST(a_rejected_document_starts_its_next_review_from_zero) { Document doc = in_review(); doc.approve("Ben"); doc.reject("Chen", "too short"); LLD_CHECK_EQ(doc.describe(), std::string{"draft (returned: too short)"}); doc.submit(); LLD_CHECK_EQ(doc.describe(), std::string{"in review (0 of 2 approvals)"}); doc.approve("Ben"); // allowed again: this is a new review LLD_CHECK_EQ(doc.status(), std::string_view{"in review"});}
// The version counts publications: revise goes back to draft at v1, and// only the second publication makes it v2. The edit is kept in the data.LLD_TEST(revising_keeps_the_version_and_republishing_raises_it) { Document doc = in_review(); doc.approve("Ben"); doc.approve("Chen"); doc.revise(); LLD_CHECK_EQ(doc.version(), 1); doc.edit("Hello again."); doc.submit(); doc.approve("Ben"); doc.approve("Chen"); LLD_CHECK_EQ(doc.version(), 2); LLD_CHECK(doc.data().content == "Hello again.");}
// Bad input is refused: no document without a title or an author, and an// empty document cannot be submitted (it stays a draft).LLD_TEST(empty_documents_and_missing_authors_are_refused) { LLD_CHECK_THROWS(Document("", "Ana", "Hello."), std::invalid_argument); LLD_CHECK_THROWS(Document("Guide", "", "Hello."), std::invalid_argument); Document doc{"Guide", "Ana", ""}; LLD_CHECK_THROWS(doc.submit(), std::logic_error); LLD_CHECK_EQ(doc.status(), std::string_view{"draft"});}
// The variant form's log must equal the state-object log line for line,// and the enum + switch log must differ in exactly two lines (in main's// output, those are steps 7 and 8).LLD_TEST(the_variant_form_tells_the_same_story) { LLD_CHECK(review_story<var::Document>() == review_story<Document>()); const std::vector<std::string> with_switch = review_story<before::Document>(); const std::vector<std::string> with_objects = review_story<Document>(); int differences = 0; for (std::size_t i = 0; i < with_objects.size(); ++i) { // Count 1 for each line that differs. Both logs have 13 lines. differences += with_switch[i] != with_objects[i] ? 1 : 0; } LLD_CHECK_EQ(differences, 2); // both caused by the leaked approval}A second C++ form: std::variant
Section titled “A second C++ form: std::variant”The state objects above are one C++ form of the pattern. C++17 added
another that fits the same problem: a std::variant holds exactly
one of several types, and knows which. Each state becomes a plain
struct with only its own data:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each state is a plain value holding only the data that stage needs.struct Draft { std::string feedback; // why a reviewer sent it back; empty if none};struct InReview { std::set<std::string> approved_by;};struct Published {}; // no data of its ownstruct Archived {};
// A State holds exactly one of the four structs at a time, and knows which.// Assigning a different struct destroys the old one first, with its data.// `using` gives the long type a short name.using State = std::variant<Draft, InReview, Published, Archived>;VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same public events as the state-object Document. The rules for each// event are written inside the event, which checks which struct state_// holds. The document is copyable for free: every member is a value.class Document final {public: Document(std::string title, std::string author, std::string content);
void edit(std::string content); void submit(); void approve(const std::string& reviewer); void reject(const std::string& reviewer, std::string reason); void revise(); void archive();
std::string_view status() const; std::string describe() const; int version() const { return data_.version; }
private: [[noreturn]] void refuse(std::string_view event) const;
DocumentData data_; State state_ = Draft{}; // every document starts as a draft with no feedback};The rules move back into the document, but the data stays with its stage, so “a draft with approvals” still cannot be written:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same rules as InReview::approve, written in the document. Throws// std::logic_error unless in review, and std::invalid_argument for the// author or a repeat reviewer.void Document::approve(const std::string& reviewer) { // A pointer to the InReview inside state_, or nullptr if state_ holds // a different struct. Note the & : get_if takes the variant's address. auto* review = std::get_if<InReview>(&state_); if (review == nullptr) { refuse("approve"); } if (reviewer == data_.author) { throw std::invalid_argument{"authors cannot approve their own document"}; } // insert returns a pair; .second is false if the name was already in // the set. Either way, nothing else has changed yet. if (!review->approved_by.insert(reviewer).second) { throw std::invalid_argument{reviewer + " already approved"}; } if (review->approved_by.size() >= required_approvals) { ++data_.version; state_ = Published{}; // `review` now points at a destroyed object: } // do not use it after this line}std::get_if<InReview>(&state_) returns a pointer to the InReview
inside the variant, or nullptr if the variant holds something else.
The same lifetime rule applies in a new shape: assigning
state_ = Published{} destroys the InReview that review points to,
so the pointer must not be used after that line.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Builds the same text as the state objects' describe(). Only the two// stages with data need their own wording; the rest use the name.std::string Document::describe() const { // An "if with an initializer": `if (setup; condition)`. `draft` exists // only inside this if. The condition reads "it is a Draft, and it has // feedback"; && stops first if draft is nullptr, so it is never used then. if (const auto* draft = std::get_if<Draft>(&state_); draft && !draft->feedback.empty()) { return "draft (returned: " + draft->feedback + ")"; } // Here the pointer itself is the condition: non-null means "in review". if (const auto* review = std::get_if<InReview>(&state_)) { return "in review (" + std::to_string(review->approved_by.size()) + " of " + std::to_string(required_approvals) + " approvals)"; } return std::string{status()}; // a draft with no feedback, published, or archived}The variant form told the same story as the state objects, line for line (“variant form agrees: yes”), and a test checks it.
How to choose
Section titled “How to choose”| Question | enum and switch |
State objects | std::variant of structs |
|---|---|---|---|
| Where does stage-only data live? | in the object, for every stage | in the state object | in the state struct |
| Can an impossible state be written? | yes: every member exists in every stage | no | no |
| Where are a stage’s rules? | spread over every event’s switch |
together, in the state’s class | spread over the document’s events |
| Adding a stage | a new enumerator; -Wswitch warns about each switch with no default that misses it, but the if chains must be found by hand |
a new class; existing states change only if they move to it | a new struct; a std::visit over an overload set fails to compile until it handles it, but the get_if checks in the events must be found by hand |
| Adding an event | one new function | a new virtual function, overridden where allowed | one new function |
| Copying the object | free | needs a clone() |
free |
| Cost per event | a switch |
a virtual call; an allocation per transition | a type check; no allocation to change stage (a stage’s own members, such as the approvals set, still allocate) |
| Fits best | few stages, no stage data | many stages, each with long rules of its own | stages with their own data, rules short enough to read in one class |
For this workflow, the std::variant form is arguably the better
default: the stage data is small, the rules are short, and copying is
free. The state-object form earns its place when each stage’s rules are
long enough that reading them together, in one class, matters more than
seeing one event across all stages.
State or Strategy?
Section titled “State or Strategy?”The class outlines look alike: an object holds another object behind an interface and delegates to it. The difference is who changes it and why:
- In Strategy, the caller chooses the object, usually once, and the strategies do not know each other. A help desk’s assignment rule does not decide what the next rule is.
- In State, the states decide the next state, as part of handling
an event.
InReviewknows that a second approval leads toPublished. The caller never picks a state; it sends events.
If the object holding the behaviour would change because of something the object itself went through, it is State. If it changes because someone outside chose a different behaviour, it is Strategy.
When to use State, and when not to
Section titled “When to use State, and when not to”Use it when:
- what an object may do depends on its stage, and some stages have data that means nothing in the others;
- the rules of one stage are long enough to deserve their own class and tests;
- stages are added over time, and adding one should not mean editing a
switchin every event.
Do not use it when:
- the stages have no data of their own and the rules are one-liners.
Use an
enum classand aswitch, as in the state diagram page. - there are many states and events, but the rules are uniform (“from A, event x goes to B”). A transition table in data, mapping (state, event) to the next state, is shorter and easy to compare with the diagram.
- what varies is chosen from outside and does not move by itself. That is Strategy.
Costs and alternatives
Section titled “Costs and alternatives”| Approach | Good for | Costs |
|---|---|---|
enum and switch |
few stages, no stage data | impossible states once stage data appears; each event’s switch grows |
| Transition table (data) | many states, uniform rules | guards and actions become functions in a table, harder to read |
| State objects | stages with long rules of their own | a class per stage; an allocation per transition; copying needs clone |
std::variant of structs |
stages with their own data, short rules | rules for all stages in one class; std::visit syntax to learn |
Common misuse
Section titled “Common misuse”- A state class for every value of a flag. “Bold” and “not bold”
are not stages of a lifecycle. Use a
bool. - States that set the context’s state and keep running. See the flawed example above.
- Shared data copied into every state. The title and version belong to the document. If each state held its own copy, a transition would have to copy them, and could forget.
- States that call each other’s functions. A state should know which state comes next, not how the others work.
- Using State to avoid deciding the rules. Every cell of the state-event table still needs a decision. The pattern only gives each decision a place.
When a requirement changes
Section titled “When a requirement changes”“Legal documents need three approvals.” The number moves from the
global constant into the document (DocumentData gains
required_approvals), and InReview::approve reads it from the data it
already receives. No stage is added; no other state changes.
“A reviewer can withdraw their approval while it is in review.” A
new event, withdraw. Add one virtual function to DocumentState with
the refusing default, override it in InReview (erase from
approved_by_), and add one forwarding line to Document. The other
three states do not change, because the default refuses for them.
“Approved documents wait for a publish date.” A new stage; see the exercise.
Exercise
Section titled “Exercise”Exercise: Add a stage, in two designs
Add FR-7: when the second approval arrives, a document with a
publish date set goes to scheduled instead of published. A
scheduled document is published when publish_due(today) is called on
or after its date. It can be cancelled, which returns it to draft.
Documents with no date are published at once, as before.
- Draw the new transitions.
- In the state-object design, which classes are new and which existing ones change? Where does the publish date live?
- In the
std::variantdesign, what changes? - In the
enumandswitchdesign, what changes, and what new impossible state could appear?
Show the explained answer
1. In review → scheduled on the second approval, if a date is set.
Scheduled → published on publish_due(today) with today on or after
the date (version + 1 then, not before). Scheduled → draft on cancel.
2.
class Scheduled final
a DocumentState
Member functions
std::unique_ptr<DocumentState> publish_due(DocumentData& doc, int today) override;on or after the day: version + 1, Publishedstd::unique_ptr<DocumentState> cancel(DocumentData& doc) override;back to Draft
interface (abstract class) DocumentState
two new events
Member functions
virtual std::unique_ptr<DocumentState> publish_due(DocumentData& doc, int today);default: refusevirtual std::unique_ptr<DocumentState> cancel(DocumentData& doc);default: refuse
The date the author sets is document data (DocumentData gains an
std::optional<int> publish_day), because it is set in a draft and
read in review. Scheduled needs no data of its own: it reads the day
from the document, and only a draft can change it. InReview::approve changes: on the second approval it returns
Scheduled when a day is set. Document gains two forwarding
functions. Draft, Published, and Archived do not change: the
defaults refuse the new events.
Should publish_due on a document that is not scheduled be refused
with an error? It will be called for every document each night, so
being refused is normal; returning “nothing to do” may be better than
throwing. This is the same refuse-or-ignore question the state diagram
page raises, and it needs a decision either way.
3. A new empty struct Scheduled {}; in the variant; approve
assigns it instead of Published{} when a day is set; two new member
functions; and the name_of overload set gains one function.
std::visit in status() fails to compile until it does. That safety
net covers only the visited functions: the events use get_if and
std::holds_alternative, so you must still read each of them to decide
whether it allows the new stage.
4. A new enumerator; a new case in approve, reject, describe, and the
name function (-Wswitch warns, because those switch statements have
no default); a check of each if chain in edit, submit, revise,
and archive, which no compiler warning finds; and two new functions.
No new member is needed, because the day lives in the document data.
The new risk is approved_by_: a scheduled document still holds its two
approvals, and cancel moves it back to draft. Unless cancel
remembers to clear them, the next review starts at two, which is the bug
this page started with, now on a second path.
Related patterns
Section titled “Related patterns”- Strategy: same shape, but the caller chooses the behaviour, and strategies do not lead to one another. See Strategy, and Strategy vs State vs Template Method.
- State diagrams and
enumstate machines: the design to start with; see state machine diagrams. - Command: turns an event into an object, so events can be queued or undone. A state machine often receives commands. See Command.
- Memento: saves a snapshot of an object’s state so it can be restored, which is different from State’s “stage of a lifecycle”. See Memento.
Summary
Section titled “Summary”- State gives each stage of a lifecycle its own object (or value) holding that stage’s data and rules; the context delegates every event to its current stage.
- Decide where each data member belongs by asking in which stages it means something. Data that means something in one stage belongs to that stage, so it is created and destroyed with it, and impossible states cannot be written.
- In C++, let each event return the next state and have the context replace the old one afterwards. A state that replaces itself destroys the object whose function is still running.
std::variantof structs is a strong alternative when stage data is small and rules are short; anenumand aswitchremain right for stages with no data.- State and Strategy look alike; in State, the stages choose the next stage, and in Strategy, the caller chooses.