Command
What you will learn on this page
Section titled “What you will learn on this page”- The problem Command solves, shown before the pattern is named: an operation that must be kept after it runs, so it can be undone, listed, or grouped.
- How to decide which data belongs to the text, which to one edit, and which to the history.
- The parts of the pattern: the command interface, the concrete commands, the receiver they act on, and the invoker that runs and keeps them.
- The rule that makes undo correct: a command stores exactly what its undo needs, including what it only learns while it runs.
- How a group of commands becomes one step, all or nothing.
- A lighter C++ form with
std::function, and what it costs.
The problem
Section titled “The problem”A notes app needs a small text editor. The first version only inserts and erases text, but users expect undo.
Requirements:
- FR-1 The user can insert text at a position and erase a number of characters at a position. An edit that does not fit the text (a position past the end, or an erase longer than the text that remains) is refused, and the text does not change.
- FR-2 The user can undo the most recent edit, again and again, back to the starting text.
- FR-3 The app shows the history in words, oldest first, such
as
insert "Hello" at 0orerase " world" at 5. - FR-4 The history keeps only the 100 most recent steps. Older steps can no longer be undone.
- FR-5 Replace all is one step: one undo puts back every replaced word.
Non-functional requirement:
- NFR-1 The memory the history uses grows with the size of the edits, not with the size of the document. A 20,000-character note with 100 small edits must not hold 100 copies of the note.
Where Command shows up in requirements. Listen for “undo”,
“redo”, “history”, “log every action”, “replay”,
“queue it”, “run it later”, “retry”, “do these as one
step”, or “the button, the menu item, and the shortcut all do the
same thing”. Each one asks for an operation that exists as a thing you
can keep, pass along, or run again, not only as a function call that
happens and is gone. Command comes up often in applications with a
user interface or a job queue. In code, the signal is a history stored
as something other than the operations themselves (copies of the whole
state, or a list of strings that is parsed again), or one switch on an
“action kind” repeated in the places that do, undo, and print an action.
The straightforward solution
Section titled “The straightforward solution”The simplest correct undo saves a copy of the whole text before every edit, and undo puts the last copy back:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Undo by saving a copy of the whole text before every edit.// The editor owns the text (a TextBuffer) and a list of earlier versions of// it. Each edit first copies the whole current text into that list; undo// throws the current text away and puts the newest copy back. It is simple// and correct, but every step costs a full copy of the document.// `final` means no class may inherit from this one.class Editor final {public: // Starts with `text` (empty by default) and remembers at most // `history_limit` steps (100 by default). `explicit` stops a plain // std::string from turning into an Editor by accident. Throws // std::invalid_argument if history_limit is 0. explicit Editor(std::string text = {}, std::size_t history_limit = 100);
// Each edit saves a copy of the text, then makes the change. Both throw // std::out_of_range (from TextBuffer) if the position or range does not // fit the text; then neither the text nor the history changes. void insert(std::size_t pos, std::string_view text); void erase(std::size_t pos, std::size_t count); bool undo(); // false if there is nothing to undo
const std::string& text() const { return buffer_.text(); } std::size_t saved_characters() const; // the memory the history holds
private: void remember(std::string snapshot); // drops the oldest past the limit
TextBuffer buffer_; // A std::deque is a sequence that can add and remove at both ends // cheaply: new copies go on the back, undo takes from the back, and the // limit drops the oldest from the front. std::deque<std::string> snapshots_; // the whole text, before each edit std::size_t limit_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Copy first, edit second, save third. The copy is taken before the edit,// because afterwards the old text is gone. It is saved only after the edit// succeeded, so a refused edit leaves no snapshot behind.void Editor::insert(std::size_t pos, std::string_view text) { std::string before_edit = buffer_.text(); // a copy of the whole text buffer_.insert(pos, text); // if this throws, nothing is saved // std::move hands the copy's characters to remember instead of copying // them a second time; before_edit is not used again. remember(std::move(before_edit));}
// The same three steps. TextBuffer::erase returns the removed characters,// but this editor does not need them: the whole old text is in the copy.void Editor::erase(std::size_t pos, std::size_t count) { std::string before_edit = buffer_.text(); buffer_.erase(pos, count); remember(std::move(before_edit));}
// Puts the newest saved copy back as the text, and forgets that copy.bool Editor::undo() { if (snapshots_.empty()) { return false; // no saved copy: nothing to undo } // Build a new TextBuffer from the newest copy, moving the string out of // the deque rather than copying it, and replace the current buffer // with it. The old current text is destroyed. buffer_ = TextBuffer{std::move(snapshots_.back())}; // The back element is now a moved-from (emptied) string; remove it. snapshots_.pop_back(); return true;}The editor uses a TextBuffer, a small class that holds the text and
knows nothing about undo. It is shown in the implementation below.
This version is correct, and the test agrees:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The snapshot editor is correct; its cost is a whole copy per step.// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one// unless the two are equal, and prints both. They come from the site's// small test header, lld_test.hpp. std::size_t{21} makes the expected value// the type saved_characters() returns, so the compiler does not warn about// comparing a signed int with an unsigned size.// The test makes two edits, checks how much text the history copied, then// undoes both and checks that the third undo finds nothing.LLD_TEST(before_snapshots_undo_correctly_but_copy_the_whole_text) { before::Editor editor{"0123456789"}; editor.insert(10, "A"); // saves 10 characters editor.erase(0, 1); // saves 11 LLD_CHECK_EQ(editor.saved_characters(), std::size_t{21}); LLD_CHECK(editor.undo()); LLD_CHECK(editor.undo()); LLD_CHECK_EQ(editor.text(), std::string{"0123456789"}); LLD_CHECK(!editor.undo()); // both copies used up: nothing left to undo}The trouble is in the requirements it does not meet.
- NFR-1 fails. Every step stores the whole text. The program below makes 100 one-character edits to a 20,000-character note, and the snapshot history ends up holding 2,004,950 characters, about a hundred copies of the note, to remember a hundred characters.
- FR-3 cannot be met. A snapshot says what the text was, not
what happened. To print
erase " world" at 5, the editor would have to compare two copies and guess. - Every new kind of edit (replace, indent, change case) becomes a
new member function on
Editorthat must remember to copy the text and callremember. Forget it once, and that edit cannot be undone.
Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”For each piece of data, ask: what is it about, and how long must it live?
| Data | It is about | It must live | So it belongs to |
|---|---|---|---|
| the text | the document | as long as the editor | the buffer |
| where to insert, and what | one insert | until that step is dropped | that insert |
| where to erase, how many, and what was erased | one erase | until that step is dropped | that erase |
| the steps that can be undone, newest last | the session | as long as the editor | the editor (history) |
| the limit of 100 | the session | as long as the editor | the editor |
The third row is the key. To undo an erase, you must put back the text it removed, and nobody knows that text until the erase actually runs. So the erase itself must record it.
Then, for each function, ask: whose data does it need?
| Function | It needs | So it belongs to |
|---|---|---|
| insert or erase characters | the text | the buffer |
| make one edit, reverse it, describe it | that edit’s data, and the text | each kind of edit |
| run an edit, keep it, undo the newest | the history | the editor |
| drop the oldest step past the limit | the history and the limit | the editor |
| find every match for replace all | the text, at the moment of the request | a free function that builds the edits |
| decide which edit the user asked for | the key, menu item, or button | the caller (the app’s UI code) |
Each kind of edit has the same three jobs (do, undo, describe) and its own data. That is a family of classes with one interface. The editor needs to call those three jobs without knowing which kind of edit it holds.
The pattern
Section titled “The pattern”That is the Command pattern.
| Role | What it does | In this example |
|---|---|---|
| Command interface | The operations every request supports | EditCommand: apply, undo, describe |
| Concrete commands | One class per kind of request; each holds its own data | InsertText, EraseText, EditGroup |
| Receiver | The object the commands act on; it does the real work | TextBuffer |
| Invoker | Runs commands and keeps them; never looks inside one | Editor |
| Client | Decides which command to create, and hands it to the invoker | main here; the UI code in a real app |
class Editor final
the invoker
Data members
TextBuffer buffer_;the receiverstd::deque<std::unique_ptr<EditCommand>> done_;newest at the backstd::size_t limit_;100 by default
Member functions
void run(std::unique_ptr<EditCommand> edit);apply, then keepbool undo();false if nothing is leftstd::vector<std::string> history() const;oldest first
interface (abstract class) EditCommand
Member functions
virtual void apply(TextBuffer& buffer) = 0;virtual void undo(TextBuffer& buffer) = 0;virtual std::string describe() const = 0;
class InsertText final
an EditCommand
Data members
std::size_t pos_;std::string text_;what to insert; also what to erase on undo
class EraseText final
an EditCommand
Data members
std::size_t pos_;std::size_t count_;std::string erased_;filled in by apply
class EditGroup final
an EditCommand
Data members
std::string description_;std::vector<std::unique_ptr<EditCommand>> edits_;applied in order
class TextBuffer final
the receiver
Data members
std::string text_;
Member functions
void insert(std::size_t pos, std::string_view text);std::string erase(std::size_t pos, std::size_t count);returns the erased text
Text description of the diagram
A solid arrow means “owns” or “creates”, a dashed arrow means “uses”, and a thick arrow means “implements”. The Client (UI code or main) creates an InsertText (it creates the other commands the same way; the diagram shows one) and uses the Editor (the invoker) by calling run with it. The Editor owns the TextBuffer (the receiver, which holds the text) and owns its EditCommand history, newest last. InsertText (pos, text), EraseText (pos, count, erased), and EditGroup (description) each implement EditCommand. EditGroup also owns other EditCommands, in order. EditCommand has a dashed arrow to TextBuffer: apply and undo act on it.
Diagram source (Mermaid)
flowchart TB
CL["Client<br/>UI code or main"] -->|creates| IN
CL -.->|"run(command)"| ED["Editor<br/>invoker"]
ED -->|owns| TB["TextBuffer<br/>receiver: the text"]
ED -->|"owns, newest last"| EC["EditCommand<br/>interface"]
IN["InsertText<br/>pos, text"] ==>|implements| EC
ER["EraseText<br/>pos, count, erased"] ==>|implements| EC
EG["EditGroup<br/>description"] ==>|implements| EC
EG -->|"owns, in order"| EC
EC -.->|"apply and undo act on"| TBNotice what the editor does not know. It has no insert or erase
of its own and no switch on the kind of edit. A new kind of edit is a
new class; the editor, the history, and the limit do not change.
The C++ implementation
Section titled “The C++ implementation”The receiver
Section titled “The receiver”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The text being edited. It knows nothing about undo.// In Command-pattern terms this is the "receiver": the object the commands// act on. It offers two edits, and each one checks first and then either// makes the whole change or throws without changing anything.class TextBuffer final {public: TextBuffer() = default; // an empty text // Takes the string by value and moves it into the member, so a caller // who passes a temporary string pays for no copy. explicit TextBuffer(std::string text) : text_{std::move(text)} {}
// Puts `text` in front of the character at `pos`. `pos` may equal the // length, which appends at the end. std::string_view is a read-only // look at someone else's characters, so passing it copies nothing. // Throws std::out_of_range if `pos` is past the end; then nothing changes. void insert(std::size_t pos, std::string_view text); // Removes `count` characters at `pos` and returns them. Throws // std::out_of_range if the range does not fit; then nothing changes. // Returning the removed characters is what lets an erase be undone. std::string erase(std::size_t pos, std::size_t count);
const std::string& text() const { return text_; }
private: std::string text_;};Two details make undo possible later. Each function either succeeds or
changes nothing, so a refused edit leaves no half-made change behind.
And erase returns the characters it removed, so the code that
calls it can keep them.
The command interface
Section titled “The command interface”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One edit, as an object that can be applied, undone, and described.// This is the Command interface: an abstract base class (every function is// `= 0`, "pure virtual", so it has no body here and no EditCommand can be// created on its own). Each kind of edit is a class derived from it, and// the editor holds edits only through this interface, so it never needs to// know which kind it has.class EditCommand {public: // Virtual, so deleting a derived command through an EditCommand pointer // (as std::unique_ptr<EditCommand> does) runs the derived destructor too. virtual ~EditCommand() = default;
// Makes the edit. If it throws, the buffer is unchanged. virtual void apply(TextBuffer& buffer) = 0; // Reverses the edit. Call only after apply succeeded, on the same text. virtual void undo(TextBuffer& buffer) = 0; // For the history list, e.g. insert "Hello" at 0. virtual std::string describe() const = 0;
protected: // Protected: only derived classes can use these. Copying through two // EditCommand references would copy only the base part ("slicing"), so // outsiders are not allowed to; the derived classes stay copyable. EditCommand() = default; EditCommand(const EditCommand&) = default; EditCommand& operator=(const EditCommand&) = default;};Three decisions are in this interface:
- The buffer is a parameter, not a member. A command does not store
a pointer to the text it edits, so it cannot dangle or point at the
wrong one, and each command can be tested on a plain
TextBufferwith no editor at all. undohas a precondition: it is called only afterapplysucceeded, on the text exactly asapplyleft it. An insert at 5 can be undone by erasing at 5 only if nothing moved the text in between. The editor guarantees this by undoing the newest step first.- The copy operations are
protected.EditCommandis abstract, so nobody can make a copy of one by value anyway. Whatprotectedblocks is assignment through base references: with twoEditCommand&,a = bwould copy only the base part and leave the rest ofaas it was (a form of slicing). The concrete commands can still use the copy operations, soInsertTextandEraseTextstay copyable.
The concrete commands
Section titled “The concrete commands”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Inserts `text` at `pos`. Everything undo needs is known when the command// is created: undo erases text_.size() characters at the same position.// `override` asks the compiler to check that each function really replaces// a virtual function of EditCommand.class InsertText final : public EditCommand {public: InsertText(std::size_t pos, std::string text) : pos_{pos}, text_{std::move(text)} {}
void apply(TextBuffer& buffer) override; void undo(TextBuffer& buffer) override; std::string describe() const override;
private: std::size_t pos_; std::string text_; // what to insert; also what to erase on undo};
// Erases `count` characters at `pos`. Which characters they are is known// only when apply runs, so apply stores them in erased_ and undo inserts// them back at `pos`.class EraseText final : public EditCommand {public: EraseText(std::size_t pos, std::size_t count) : pos_{pos}, count_{count} {}
void apply(TextBuffer& buffer) override; void undo(TextBuffer& buffer) override; std::string describe() const override;
private: std::size_t pos_; std::size_t count_; std::string erased_; // filled in by apply: undo needs it back};
// Several edits that apply, and undo, as one step.// A group is itself an EditCommand, so the editor treats it like any other// edit. It owns its edits through std::unique_ptr (one owner each; they are// destroyed with the group). apply runs them in order and is all or// nothing; undo runs their undos newest first.class EditGroup final : public EditCommand {public: // Takes the vector by value: the caller std::moves its edits in. // Throws std::invalid_argument if any of the pointers is null. EditGroup(std::string description, std::vector<std::unique_ptr<EditCommand>> edits);
void apply(TextBuffer& buffer) override; void undo(TextBuffer& buffer) override; std::string describe() const override { return description_; }
private: std::string description_; std::vector<std::unique_ptr<EditCommand>> edits_; // applied in order};
// Builds one group that replaces every `from` in `text` with `to`.// It only builds the group; nothing is changed until the group is applied,// and it must be applied to this same text, because the positions were// found in it. Throws std::invalid_argument if `from` is empty.std::unique_ptr<EditCommand> replace_all(std::string_view text, std::string_view from, std::string_view to);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each apply and undo is one line: the command forwards the work to the// buffer it is given. If the buffer throws, the exception passes straight on to// the caller and nothing has changed.void InsertText::apply(TextBuffer& buffer) { buffer.insert(pos_, text_); }// Erase exactly the characters apply put in: the same position, and as many// as text_ holds. The removed text that erase returns is not needed.void InsertText::undo(TextBuffer& buffer) { buffer.erase(pos_, text_.size()); }// \" is a double quote inside a string literal, so this gives, for example,// insert "Hello" at 0. std::to_string turns the number into text.std::string InsertText::describe() const { return "insert \"" + text_ + "\" at " + std::to_string(pos_);}
// buffer.erase runs first; erased_ is assigned only if it returned, so a// refused erase leaves the command as it was.void EraseText::apply(TextBuffer& buffer) { erased_ = buffer.erase(pos_, count_); }// Put the saved characters back where they came from.void EraseText::undo(TextBuffer& buffer) { buffer.insert(pos_, erased_); }// Uses erased_, so it reads well only after apply: before, it says erase "" at 5.std::string EraseText::describe() const { return "erase \"" + erased_ + "\" at " + std::to_string(pos_);}Each command stores what its undo needs, and nothing more:
InsertTextknows its text from the start, so undo erases that many characters at the same position.EraseTextknows only a position and a count when it is created. The characters it removes are known only duringapply, soapplyrecords them inerased_, andundoinserts them back.erased_is assigned only afterbuffer.erasesucceeds, so a refused erase leaves the command as it was. This is the heart of a correct undo: ifundotried to find the erased text some other way, it would have nothing to find.
describe reads erased_ too, which is why the history can say
erase " world" at 5. Before apply runs, the same command describes
itself as erase "" at 5. That is fine here, because only the editor’s
history calls describe, and it holds only commands that ran.
The invoker
Section titled “The invoker”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Runs edits and keeps the ones it may need to undo.// This is the "invoker": it owns the text and the history, but it has no// insert or erase of its own. It only calls apply, undo, and describe// through the EditCommand interface, so a new kind of edit needs no change// here.class Editor final {public: // Throws std::invalid_argument if history_limit is 0. explicit Editor(std::string text = {}, std::size_t history_limit = 100);
// Applies the edit, then keeps it. If apply throws, nothing is kept. // The std::unique_ptr is taken by value, so the caller must hand the // command over (with std::move, or straight from std::make_unique), and // the editor becomes its owner. Throws std::invalid_argument if it is null. void run(std::unique_ptr<EditCommand> edit); bool undo(); // false if there is nothing to undo
std::vector<std::string> history() const; // oldest first const std::string& text() const { return buffer_.text(); }
private: TextBuffer buffer_; // The edits that ran, each owned by its std::unique_ptr. A deque, because // undo removes from the back and the limit removes from the front. std::deque<std::unique_ptr<EditCommand>> done_; // newest at the back std::size_t limit_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Apply first, keep second. If apply throws, the exception leaves run, and// the parameter `edit` destroys the command on the way out, so the history// never holds an edit that did not happen.void Editor::run(std::unique_ptr<EditCommand> edit) { if (!edit) { // a null std::unique_ptr converts to false throw std::invalid_argument{"no edit to run"}; } edit->apply(buffer_); // if this throws, the edit is not kept // Move ownership into the history; `edit` is null after this line. done_.push_back(std::move(edit)); if (done_.size() > limit_) { done_.pop_front(); // the oldest step can no longer be undone }}
// Undo the newest edit, then forget it. Newest first is what makes each// undo safe: the text is exactly as that edit's apply left it.bool Editor::undo() { if (done_.empty()) { return false; } done_.back()->undo(buffer_); // Removing the std::unique_ptr from the deque destroys the command. // (If undo had thrown, this line would not run and the edit would stay.) done_.pop_back(); return true;}
// One line of text per kept edit, oldest first, for the history list.std::vector<std::string> Editor::history() const { std::vector<std::string> lines; for (const auto& edit : done_) { lines.push_back(edit->describe()); } return lines;}run applies first and keeps second. If apply throws, the
command is destroyed when run exits and the history is unchanged, so
FR-1’s “refused, and nothing changes” holds for the history too. The
history is a std::deque, because steps leave from both ends: undo
takes the newest from the back, and the limit drops the oldest from the
front.
Text description of the diagram
A solid arrow is the flow. The client creates a command and calls editor.run with it. If apply does not succeed, the error goes to the caller, the command is destroyed, and the history is unchanged. If it succeeds, the command is kept at the back of the history. If the history then holds more than the limit, the oldest command is dropped from the front and can no longer be undone. If it does not, the command stays until, later, editor.undo runs the newest command’s undo, and that command is removed from the back and destroyed.
Diagram source (Mermaid)
flowchart TB
A["client creates a command"] --> B["editor.run(command)"]
B --> C{"apply succeeds?"}
C -->|no| D["error to the caller<br/>command destroyed, history unchanged"]
C -->|yes| E["kept at the back of the history"]
E --> F{"more than the limit?"}
F -->|yes| G["oldest dropped from the front<br/>can no longer be undone"]
F -->|"no, later"| H["editor.undo()"]
H --> I["newest command's undo runs"]
I --> J["removed from the back and destroyed"]A group as one step
Section titled “A group as one step”FR-5 asks for “replace all” to undo in one step. A group is itself a command, holding other commands:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// All or nothing: if one edit fails, the ones already made are undone,// newest first, and the error is passed on.void EditGroup::apply(TextBuffer& buffer) { // How many edits have succeeded so far. It is declared outside the try // block so the catch block can still read it. std::size_t applied = 0; try { // The loop's counter is `applied` itself (the empty first part of // the for means "already set up"). When edit number `applied` // throws, the ++ does not run, so `applied` is exactly the number // of edits that succeeded: 0 to applied - 1. for (; applied < edits_.size(); ++applied) { edits_[applied]->apply(buffer); } } catch (...) { // `...` catches an exception of any type // --applied lowers the count first and then uses it as the index, // so this undoes edits applied - 1, then applied - 2, ... down to 0: // newest first. The edit that threw changed nothing (apply promises // that), so it is skipped. while (applied > 0) { edits_[--applied]->undo(buffer); } // A bare `throw;` rethrows the same exception, so the caller still // learns why the group failed. throw; }}
// Undo every edit, last to first. rbegin() and rend() are reverse// iterators: ++ moves them from the back of the vector towards the front.void EditGroup::undo(TextBuffer& buffer) { for (auto edit = edits_.rbegin(); edit != edits_.rend(); ++edit) { // *edit is the std::unique_ptr in the vector; -> calls through it. (*edit)->undo(buffer); }}
std::unique_ptr<EditCommand> replace_all(std::string_view text, std::string_view from, std::string_view to) { // An empty `from` would match everywhere, and the search below would // never move forward. if (from.empty()) { throw std::invalid_argument{"cannot replace an empty string"}; } // Step 1: find the start of every match, left to right. find returns // std::string_view::npos ("no position") when there is no more match. // Each new search starts just after the previous match, so matches // never overlap: in "aaa", "aa" is found once, at 0. std::vector<std::size_t> found; for (auto pos = text.find(from); pos != std::string_view::npos; pos = text.find(from, pos + from.size())) { found.push_back(pos); } // Work from the last match back, so earlier positions stay correct. // Step 2: for each match, last first, an erase of the old word followed // by an insert of the new one at the same position. The reverse // iterators visit `found` from its back; *pos is one match position. // std::string{to} makes the owned copy that InsertText keeps. std::vector<std::unique_ptr<EditCommand>> edits; for (auto pos = found.rbegin(); pos != found.rend(); ++pos) { edits.push_back(std::make_unique<EraseText>(*pos, from.size())); edits.push_back(std::make_unique<InsertText>(*pos, std::string{to})); } // Step 3: wrap the edits in one group, with a label that ends with the // number of matches, such as replace "team" with "crew" (2). The edits // are moved in, so the group becomes their only owner. The returned // std::unique_ptr<EditGroup> converts to std::unique_ptr<EditCommand>. return std::make_unique<EditGroup>("replace \"" + std::string{from} + "\" with \"" + std::string{to} + "\" (" + std::to_string(found.size()) + ")", std::move(edits));}How this code works: EditGroup::apply and replace_all
Building the group. The test replace_all_is_one_step_in_the_history
calls replace_all("a cat, a cat, a dog", "cat", "lion").
- The search loop finds “cat” at 2, then searches again from 2 + 3 = 5
and finds it at 9, then searches from 12 and finds nothing. So
foundis[2, 9]. - The second loop walks
foundbackwards, adding two edits per match. The group holds, in order: erase 3 at 9, insert “lion” at 9, erase 3 at 2, insert “lion” at 2. - The label is
replace "cat" with "lion" (2). Nothing has changed in the text yet:replace_allonly builds the group.
Applying the group. editor.run calls the group’s apply, which
applies the four edits in order:
applied |
Edit | Text afterwards |
|---|---|---|
| 0 | erase 3 at 9 | a cat, a , a dog |
| 1 | insert “lion” at 9 | a cat, a lion, a dog |
| 2 | erase 3 at 2 | a , a lion, a dog |
| 3 | insert “lion” at 2 | a lion, a lion, a dog |
The first two edits change only the text from position 9 onwards, so the
“cat” at 2 is still where replace_all found it.
When an edit fails. In the test a_group_is_all_or_nothing, the
buffer is abc and the group is “insert d at 3”, then “erase 1 at 9”.
appliedis 0: the insert works, the text isabcd, and++appliedmakes it 1.appliedis 1: the erase throwsstd::out_of_range, because 9 is past the end. The++appliedis skipped, soappliedstays 1: one edit succeeded.- The
catchblock runs.--appliedmakes it 0, andedits_[0]->undoerases thed. The text isabcagain,appliedis 0, and the loop stops. throw;sends the samestd::out_of_rangeon to the caller, which learns that the group failed and why.
Undoing the group runs the four undos from last to first: erase
“lion” at 2 and put “cat” back, then the same at 9. Each undo finds the
text exactly as its own apply left it.
- All or nothing. If the third edit in a group fails, the first two
are undone, newest first, and the error is passed on. The group never
leaves the text half replaced. (This relies on each edit’s
undonot throwing. Apart from running out of memory, that holds here: undoing an edit that just succeeded always fits the text.) - Undo in reverse order, for the same reason the editor undoes the
newest step first: each
undoexpects the text as its ownapplyleft it. replace_allworks from the last match back. In"a cat, a cat, a dog", replacing the “cat” at 9 with “lion” makes the text one character longer from 9 onwards, but it does not move the “cat” at 2, so the earlier position it found stays correct. Working front to back, the first replacement would shift the second match to 10, and the edit recorded for 9 would cut the wrong characters. The testreplace_all_is_one_step_in_the_historyuses exactly this text. (The usage below replaces “team” with “crew”, which have the same length, so it would work in either order.)- No matches is still a step.
replace_allwith nothing to replace returns an empty group, which would appear in the history asreplace "x" with "y" (0)and undo nothing. A real editor would not run it; this example leaves that choice to the caller. - It is built for one text.
replace_allreads the text to find the positions, so the group it returns must be run on that same text, right away. The usage below does exactly that.
A command that holds other commands of the same interface is the shape
of the Composite pattern. The editor neither knows nor cares: a group
is one entry in the history, with one undo.
Ownership and lifetime
Section titled “Ownership and lifetime”| Object | Owner | Lives |
|---|---|---|
TextBuffer |
the Editor, by value |
as long as the editor |
| A command, before it runs | the client, through std::unique_ptr |
until it is moved into run |
| A command that ran | the editor’s done_ |
until it is undone, or dropped past the limit |
| A command that failed | run’s parameter |
destroyed by the end of the run(...) call, before any catch runs |
| The edits inside a group | the EditGroup, through std::unique_ptr |
as long as the group |
| The buffer, in a command | nobody: it is a TextBuffer& parameter for one call |
only during apply or undo |
The last row is why no command can dangle: no command stores a pointer
or reference to anything it does not own. run takes the
std::unique_ptr by value, so the signature itself says “the
editor takes this command”; after the call, the client’s pointer is
null.
One edit and its undo, step by step
Section titled “One edit and its undo, step by step”Text description of the diagram
The client calls run on the Editor, passing an EraseText for position 5 and count 6. The Editor calls apply on the command, passing its buffer. The command calls erase(5, 6) on the TextBuffer, which returns “ world”. The command stores “ world” in erased_. The Editor then pushes the command onto the back of done_. Later, the client calls undo on the Editor. The Editor calls undo on the command, passing its buffer, and the command calls insert(5, “ world”) on the TextBuffer. The Editor then pops the command off done_, which destroys it.
Diagram source (Mermaid)
sequenceDiagram
participant C as client
participant E as Editor
participant X as EraseText(5, 6)
participant B as TextBuffer
C->>E: run(command)
E->>X: apply(buffer_)
X->>B: erase(5, 6)
B-->>X: " world"
X->>X: erased_ = " world"
E->>E: done_.push_back(command)
C->>E: undo()
E->>X: undo(buffer_)
X->>B: insert(5, " world")
E->>E: done_.pop_back(): command destroyedVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The client creates each command with std::make_unique and hands it// straight to run, which becomes its owner. The text after each step:// "Helo world", "Hello world", "Hello", "Hello, team. Thanks, team".Editor editor;editor.run(std::make_unique<InsertText>(0, "Helo world"));editor.run(std::make_unique<InsertText>(3, "l")); // fix the typoeditor.run(std::make_unique<EraseText>(5, 6)); // remove " world"editor.run(std::make_unique<InsertText>(5, ", team. Thanks, team"));std::cout << "after four edits:\n";show(editor);
// The text has 25 characters, so position 40 is past the end:// TextBuffer::erase throws std::out_of_range, run lets it pass, and the// command is destroyed without being kept. The text is unchanged.try { editor.run(std::make_unique<EraseText>(40, 1));} catch (const std::out_of_range& error) { std::cout << "refused: " << error.what() << '\n';}
// replace_all reads the current text to find the matches (at 7 and 21)// and returns one group; run applies it as a single step.editor.run(replace_all(editor.text(), "team", "crew"));std::cout << "after replace all:\n";show(editor);std::cout << "history:\n";for (const std::string& line : editor.history()) { std::cout << " " << line << '\n';}
// The first undo reverses the whole group (both words); the second// removes ", team. Thanks, team". undo returns false once nothing is// left, which ends the while loop after the remaining three steps.std::cout << "undo twice:\n";editor.undo();show(editor);editor.undo();show(editor);int undone = 0;while (editor.undo()) { ++undone;}std::cout << "undid " << undone << " more; nothing left to undo\n";show(editor);How this code works: The usage, step by step
The history column shows what done_ holds after each line, oldest
first.
| Step | Text afterwards | History |
|---|---|---|
| insert “Helo world” at 0 | Helo world |
1 edit |
| insert “l” at 3 | Hello world |
2 edits |
| erase 6 at 5 | Hello |
3 edits |
| insert “, team. Thanks, team” at 5 | Hello, team. Thanks, team |
4 edits |
| erase 1 at 40: refused | unchanged (25 characters) | still 4: the command was destroyed |
| replace “team” with “crew” (at 21, 7) | Hello, crew. Thanks, crew |
5 entries: the group is one |
| undo | Hello, team. Thanks, team |
4: the group is undone and destroyed |
| undo | Hello |
3 |
undo, undo, undo (undone becomes 3) |
Hello world, Helo world, empty |
0 |
| one more undo | empty | 0: undo returns false, the loop ends |
Every undo works on the newest command, and each one finds the text as
its own apply left it. That is why undoing the erase can put
" world" back at 5: the text is Hello again by then.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The std::function form of the same idea. The erase's apply lambda// saves " world" in the shared string; the undo lambda reads it back.fn::Editor light;light.run(fn::insert_text(0, "Hello world"));light.run(fn::erase_text(5, 6));std::cout << "function form: \"" << light.text() << "\"";light.undo();std::cout << ", after undo: \"" << light.text() << "\"\n";VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 100 one-character edits to a 20,000-character document.// Both editors get the same edits. std::string(20'000, 'x') is 20,000// copies of 'x'; the ' in 20'000 only makes the number easier to read.// The snapshot editor copies the whole text before each insert: 20,000// characters, then 20,001, ..., then 20,099, which adds up to 2,004,950.// The command editor keeps 100 InsertText commands of one "y" each.// Both stay within the default limit of 100 steps, so nothing is dropped.before::Editor snapshots{std::string(20'000, 'x')};Editor commands{std::string(20'000, 'x')};for (std::size_t i = 0; i < 100; ++i) { snapshots.insert(i, "y"); commands.run(std::make_unique<InsertText>(i, "y"));}std::cout << "snapshot history holds " << snapshots.saved_characters() << " characters of text\n";std::cout << "command history holds " << commands.history().size() << " edits of 1 character each\n";// ?: picks "yes" if the two texts are equal, otherwise "no".std::cout << "same text: " << (snapshots.text() == commands.text() ? "yes" : "no") << '\n';after four edits: text: "Hello, team. Thanks, team"refused: cannot erase 1 at 40after replace all: text: "Hello, crew. Thanks, crew"history: insert "Helo world" at 0 insert "l" at 3 erase " world" at 5 insert ", team. Thanks, team" at 5 replace "team" with "crew" (2)undo twice: text: "Hello, team. Thanks, team" text: "Hello"undid 3 more; nothing left to undo text: ""function form: "Hello", after undo: "Hello world"snapshot history holds 2004950 characters of textcommand history holds 100 edits of 1 character eachsame text: yesRead the output against the requirements:
- The erase at position 40 is refused (FR-1), and it does not appear in the history.
- The history lists five steps in words (FR-3). Replace all is one of them, and the first undo puts both words back at once (FR-5).
- The second undo removes
, team. Thanks, team, and three more undos return to the empty starting text (FR-2). A sixth undo reports that nothing is left. - The snapshot editor and the command editor end with the same text, but the snapshot history holds 2,004,950 characters: each of the 100 copies is the whole note at that moment (20,000 characters, then 20,001, and so on). The command history holds the 100 inserted characters, plus a position and a string object for each command (NFR-1).
The tests check each rule on its own. The first one tests commands with no editor at all, which the “buffer as a parameter” decision made possible:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST, LLD_CHECK, and LLD_CHECK_EQ are explained above the first// test. LLD_CHECK_THROWS(expression, type) fails unless the expression// throws an exception of that type.
// Each command is tested alone, on a plain buffer, with no editor.// Proves that undo exactly reverses apply, for an erase and an insert, and// that an erase describes the characters it removed.LLD_TEST(each_command_undoes_exactly_what_it_did) { TextBuffer buffer{"Hello world"}; EraseText erase{5, 6}; erase.apply(buffer); LLD_CHECK_EQ(buffer.text(), std::string{"Hello"}); LLD_CHECK_EQ(erase.describe(), std::string{"erase \" world\" at 5"}); erase.undo(buffer); LLD_CHECK_EQ(buffer.text(), std::string{"Hello world"});
InsertText insert{5, ","}; insert.apply(buffer); LLD_CHECK_EQ(buffer.text(), std::string{"Hello, world"}); insert.undo(buffer); LLD_CHECK_EQ(buffer.text(), std::string{"Hello world"});}
// Three refused runs: an insert past the end of "abc" (4 > 3), an erase of// 3 characters starting at 1 (only 2 are left), and no command at all.// Proves that the text, the history, and undo all behave as if none of// them had been tried.LLD_TEST(a_refused_edit_changes_nothing_and_is_not_kept) { Editor editor{"abc"}; LLD_CHECK_THROWS(editor.run(std::make_unique<InsertText>(4, "x")), std::out_of_range); LLD_CHECK_THROWS(editor.run(std::make_unique<EraseText>(1, 3)), std::out_of_range); LLD_CHECK_THROWS(editor.run(nullptr), std::invalid_argument); LLD_CHECK_EQ(editor.text(), std::string{"abc"}); LLD_CHECK(editor.history().empty()); LLD_CHECK(!editor.undo());}
// A group whose first edit works ("abc" becomes "abcd") and whose second// fails (position 9 is past the end). Proves that apply undoes the first// edit before passing the exception on, so the buffer is back to "abc".// The vector is moved into the group, which then owns both edits.LLD_TEST(a_group_is_all_or_nothing) { TextBuffer buffer{"abc"}; std::vector<std::unique_ptr<EditCommand>> edits; edits.push_back(std::make_unique<InsertText>(3, "d")); // fine edits.push_back(std::make_unique<EraseText>(9, 1)); // fails EditGroup group{"two edits", std::move(edits)}; LLD_CHECK_THROWS(group.apply(buffer), std::out_of_range); LLD_CHECK_EQ(buffer.text(), std::string{"abc"}); // the first edit was undone}
// "cat" is at 2 and 9; "lion" is one character longer, so this also proves// that working from the last match back keeps the positions right.// Proves the whole replacement is one history entry and one undo, and that// an empty `from` is refused.LLD_TEST(replace_all_is_one_step_in_the_history) { Editor editor{"a cat, a cat, a dog"}; editor.run(replace_all(editor.text(), "cat", "lion")); LLD_CHECK_EQ(editor.text(), std::string{"a lion, a lion, a dog"}); const std::vector<std::string> history = editor.history(); LLD_CHECK_EQ(history.size(), std::size_t{1}); LLD_CHECK_EQ(history.front(), std::string{"replace \"cat\" with \"lion\" (2)"}); LLD_CHECK(editor.undo()); LLD_CHECK_EQ(editor.text(), std::string{"a cat, a cat, a dog"}); LLD_CHECK_THROWS(replace_all("abc", "", "x"), std::invalid_argument);}
// A limit of 2 and three edits: the first edit ("a") is dropped from the// history, so only "c" and "b" can be undone and "a" stays in the text.// Also proves a limit of 0 is refused.LLD_TEST(the_history_keeps_only_the_newest_steps) { Editor editor{"", 2}; editor.run(std::make_unique<InsertText>(0, "a")); editor.run(std::make_unique<InsertText>(1, "b")); editor.run(std::make_unique<InsertText>(2, "c")); LLD_CHECK(editor.undo()); LLD_CHECK(editor.undo()); LLD_CHECK(!editor.undo()); // the first step was dropped LLD_CHECK_EQ(editor.text(), std::string{"a"}); LLD_CHECK_THROWS(Editor("", 0), std::invalid_argument);}
// The same two edits through both forms give the same text ("Hello!"),// and two undos take both back to "Hello world". fn::Edit{"empty", {}, {}}// has empty functions (`{}` makes an empty std::function), which run// refuses with std::invalid_argument.LLD_TEST(the_function_form_gives_the_same_text) { Editor with_classes{"Hello world"}; fn::Editor with_functions{"Hello world"}; with_classes.run(std::make_unique<EraseText>(5, 6)); with_functions.run(fn::erase_text(5, 6)); with_classes.run(std::make_unique<InsertText>(5, "!")); with_functions.run(fn::insert_text(5, "!")); LLD_CHECK_EQ(with_functions.text(), with_classes.text()); with_classes.undo(); with_functions.undo(); with_classes.undo(); with_functions.undo(); LLD_CHECK_EQ(with_functions.text(), std::string{"Hello world"}); LLD_CHECK_THROWS(with_functions.run(fn::Edit{"empty", {}, {}}), std::invalid_argument);}The lighter form: std::function
Section titled “The lighter form: std::function”A command class with one or two short functions can feel heavy. C++ can
hold “something to call later” in std::function, so a command can be
a plain struct of two functions and a label:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An edit as two functions and a label, with no class hierarchy.// std::function<void(TextBuffer&)> can hold anything that can be called// with a TextBuffer& and returns nothing: here, always a lambda. An empty// std::function holds nothing and converts to false.struct Edit { std::string description; std::function<void(TextBuffer&)> apply; std::function<void(TextBuffer&)> undo;};
// Each builds an Edit whose two lambdas do the work; nothing runs yet.Edit insert_text(std::size_t pos, std::string text);Edit erase_text(std::size_t pos, std::size_t count);
// The same invoker idea as the class version: apply, then keep, and undo// the newest first. It stores Edit values directly; no pointers are needed,// because every Edit has the same type.class Editor final {public: explicit Editor(std::string text = {}) : buffer_{std::move(text)} {}
void run(Edit edit); // throws std::invalid_argument if a function is empty bool undo(); const std::string& text() const { return buffer_.text(); }
private: TextBuffer buffer_; std::vector<Edit> done_; // no limit, to keep the sketch short};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The length and the label are worked out first, while `text` still holds// the characters; the lambda below then moves `text` into itself.Edit insert_text(std::size_t pos, std::string text) { const std::size_t length = text.size(); std::string label = "insert \"" + text + "\" at " + std::to_string(pos); // The braces build the Edit member by member: description, apply, undo. // apply: [pos, text = std::move(text)] stores a copy of pos and moves // the string into the lambda, so the lambda owns its own text. // undo: needs only the position and the length to erase. return {std::move(label), [pos, text = std::move(text)](TextBuffer& buffer) { buffer.insert(pos, text); }, [pos, length](TextBuffer& buffer) { buffer.erase(pos, length); }};}
// apply learns the erased text and undo needs it, so the two lambdas must// share it. A class would use a data member; here it is a shared_ptr.// Both lambdas capture a copy of the shared_ptr `erased`, so both point at// one string, which lives as long as either lambda does. apply writes the// removed characters into it (*erased is the string itself); undo reads// them back. The label is made now, before anything is erased, so it can// give only the count, not the characters.Edit erase_text(std::size_t pos, std::size_t count) { auto erased = std::make_shared<std::string>(); // one empty string, shared return {"erase " + std::to_string(count) + " at " + std::to_string(pos), [pos, count, erased](TextBuffer& buffer) { *erased = buffer.erase(pos, count); }, [pos, erased](TextBuffer& buffer) { buffer.insert(pos, *erased); }};}The insert is short and clear: each lambda captures what it needs by
value. The erase shows the catch. apply learns the erased text and
undo needs it, but they are two separate lambdas, each with its own
copies of what it captured. In the class, erased_ was one data member
both functions could see. Here, the shared data must be put somewhere
both lambdas point to, a std::shared_ptr<std::string>, and the
description cannot include the erased text, because it is built before
anything is erased (erase 6 at 5 instead of erase " world" at 5).
One more catch: copying an Edit copies its lambdas, and both copies
then share the same erased text, which is surprising if both are ever
run.
| Question | Command classes | std::function struct |
|---|---|---|
| Data shared by do and undo | a data member | a shared_ptr both lambdas capture |
| Adding an operation (redo, merge, save) | a new virtual function | a new std::function member in every edit |
| Testing one edit alone | create it and call it | the same |
| Names in a debugger or a stack trace | EraseText::apply |
a lambda with a compiler-generated name |
| Move-only captured data | fine | not allowed before C++23: std::function must be copyable (C++23 adds std::move_only_function) |
| Fits best | edits with state, or more than two operations | short, stateless actions, such as button callbacks |
For a command that only needs to run (a menu item, a queued job
that is never undone), a single std::function<void()> is often all
the pattern you need. Undo, with its shared state, is where classes
start to win.
Other uses of the same idea
Section titled “Other uses of the same idea”Undo is the most visible use, but the same move, an operation as an object, appears in other forms:
- Queues and background work. A job queue holds commands; a worker thread takes one and runs it. The owner of the queue never knows what the jobs do. The lifetime rule becomes strict: a queued command must own, or share, everything it touches, because the code that created it may be gone by the time it runs.
- Logs and replay. If each command can be written down (a
describethat can be read back), the log of commands is enough to rebuild the state by running them again. - One action, many triggers. A toolbar button, a menu item, and a keyboard shortcut can all hold the same command, so the action is written once.
- Macros and transactions. A group, as above, turns several commands into one, with all-or-nothing behaviour.
Command, Strategy, or a plain function call?
Section titled “Command, Strategy, or a plain function call?”| Question | Command | Strategy | A plain call |
|---|---|---|---|
| What is the object? | one request, with its own data | one way of doing a job | there is no object |
| How long does it live? | from request until undone, dropped, or run | as long as the object that uses it | the call |
| How many times does it run? | once (and once more to undo, or redo) | every time the job is done | once |
| Who chooses it? | the client, per request | configuration, usually once | the caller |
If an operation does not need to be kept for any reason, it does not need to be a command. Call the function.
When to use it
Section titled “When to use it”Use Command when the requirements ask you to keep operations:
- undo and redo, especially when the state is large and edits are small;
- a history or log that says what happened;
- several operations that must act as one step;
- operations that are created in one place and run in another, later, or on another thread;
- the same action reachable from several parts of a user interface.
Do not use it when:
- the operation runs once and nothing remembers it (a plain call is clearer);
- the state is small and cheap to copy (snapshots are simpler and cannot get undo wrong);
- the operation cannot be reversed, such as sending an email or
charging a card. “Undo” there is a new, compensating operation (a
correction email, a refund) with its own rules, not a reversal. The
command structure can still help with logging and retrying, but do
not pretend
undoexists.
- A class per kind of operation, and an allocation per command run.
- Undo is only as correct as what each command recorded. A command
that forgets to store something its undo needs fails silently, often
much later. Each command needs a test that applies, undoes, and
compares, as
each_command_undoes_exactly_what_it_diddoes. - Order matters. Undo is correct only in reverse order, on the text
as the command left it. Anything that changes the text outside the
history (a paste that bypasses
run, a second editor on the same buffer) breaks every command still in it. - Memory is proportional to the edits, but not zero. Each command is a heap object; a history of a million single-character edits is a million objects. Real editors merge consecutive typing into one step.
Common misuse
Section titled “Common misuse”- Commands that reach into the invoker. A command that calls back into the editor to change its history couples both ways. A command acts on its receiver; the invoker manages commands.
- Commands that store raw pointers to things they do not own. In a queue, the pointed-to object may be destroyed before the command runs. Pass the receiver as a parameter, as here, or own or share it.
- Undo that recomputes instead of recording. An
EraseText::undothat tried to work out the erased text from the current text would have nothing to work from. Record duringapply. - A command class for every member function in the program. Only operations that must be kept, queued, or undone need to be commands. Wrapping everything adds a class per call and no benefit.
- A
switchon a command “type” field. If the invoker checks what kind of command it holds, the interface is missing a function.
When the requirements change
Section titled “When the requirements change”| New requirement | What changes |
|---|---|
| Redo | only Editor: a second list for undone steps (the exercise below) |
| Typing a word is one undo step, not one per letter | Editor merges a new InsertText into the newest one when it continues it; InsertText needs a way to extend itself |
| The limit counts characters, not steps | only Editor: it sums what each command holds and drops from the front |
| Save the history and restore it after a restart | each command gains a way to write itself out and be read back; a function maps a saved line to a new command |
| Two people edit the same text at once | beyond this design: positions recorded by one person’s commands move when the other person edits. Collaborative editors use techniques built for that problem |
Exercise
Section titled “Exercise”Exercise: Add redo
Users want redo: after one or more undos, redo applies the undone steps again, the most recently undone step first. As in most editors, running a new edit after an undo makes the undone steps impossible to redo.
- What new data member does
Editorneed, and what type should it be? - Write
undo()andredo(). What happens to ownership of a command as it moves between them? - Why must
runclear the redo steps? Describe a short sequence of edits that would corrupt the text if it did not. - Does any command class change? In particular, is it safe to call
EraseText::applya second time on the same object?
Show the explained answer
1. A second container, for commands that were undone:
std::vector<std::unique_ptr<EditCommand>> undone_, newest undo at the
back. A std::vector is enough because it only grows and shrinks at
the back, and it never holds more steps than the history did, so the
limit already bounds it.
class Editor final
the invoker
Data members
TextBuffer buffer_;std::deque<std::unique_ptr<EditCommand>> done_;newest at the backstd::vector<std::unique_ptr<EditCommand>> undone_;newest undo at the backstd::size_t limit_;
Member functions
void run(std::unique_ptr<EditCommand> edit);apply, keep, and clear undone_bool undo();undo the newest; move it to undone_bool redo();apply the newest undone again; move it back to done_
2. The command object moves between the two lists; it is never copied or created again:
// Undo the newest step, then move its command to undone_ instead of// destroying it, so redo can apply it again later.bool Editor::undo() { if (done_.empty()) { return false; } done_.back()->undo(buffer_); // std::move hands the command's ownership to undone_: the // std::unique_ptr left at the back of done_ becomes null. undone_.push_back(std::move(done_.back())); done_.pop_back(); // removes that null pointer; the command lives on return true;}
// The mirror image: apply the newest undone step again, and move its// command back to done_.bool Editor::redo() { if (undone_.empty()) { return false; } undone_.back()->apply(buffer_); // the text is as it was when it was undone done_.push_back(std::move(undone_.back())); undone_.pop_back(); return true;}run gains one line at the end, undone_.clear();, which destroys the
steps that can no longer be redone.
Both functions change the text before push_back, so they share the
gap the callout describes for run: if push_back threw
std::bad_alloc, the change would be made but the command would stay
in the old list, and a second call would make the change twice. The
same fix applies: move the command into the other list first, and move
it back if the change throws.
3. Redo replays a command on the text as it was right after that
command was undone. A new edit changes that text. For example, start
with Hello world, erase " world" at 5, and undo it. Now insert
"!" at 0, giving !Hello world. A redo of the erase would remove 6
characters at 5, giving !Helld (wrong), because every position after
the insert moved by one. Clearing the redo steps in run rules this
out.
4. No command class changes. Calling EraseText::apply again is
safe: it erases the same range from the same text and overwrites
erased_ with the same characters. EditGroup works too, because it
applies its edits in order again. This is where the undo precondition
pays off: redo is just apply called on the text the command expects.
Related patterns
Section titled “Related patterns”- Memento: saves a copy of an object’s state so it can be restored. The snapshot editor on this page is the idea in its plainest form; see Memento. Command and Memento are often combined: a command that cannot easily be reversed keeps a memento of what it changed.
- Composite:
EditGroupis a command made of commands, which is the Composite shape. - Strategy: also an object behind an interface, but it is a way of doing a job, kept and reused; a command is one request. See Strategy.
- State: a state machine often receives commands as its events. See State.
Summary
Section titled “Summary”- Command turns a request into an object holding what it needs to run and, when needed, to be reversed. The invoker runs, keeps, lists, and undoes commands without knowing what they do.
- Sort the data first: the text belongs to the receiver, each edit’s details to that edit, and the list of steps to the invoker.
- A command must record what its undo needs, including what it
learns only while it runs, as
EraseTextrecords the erased text. - Undo is correct only in reverse order, on the state the command left. A group of commands is one step, applied all or nothing and undone in reverse.
- In C++, pass the receiver as a parameter and hold commands through
std::unique_ptr, so nothing dangles.std::functionis a lighter form for actions that only run; for undo with shared data, classes are usually clearer. - Snapshots are a fine design when the state is small. Command earns its place when the state is large, the edits are small, or the history must say what happened.