Memento
What you will learn on this page
Section titled “What you will learn on this page”- What the Memento pattern is for: saving an object’s state so that it can be put back later, as undo, “revert to saved”, or a checkpoint before a risky step.
- How to do it without breaking encapsulation: the object makes its own snapshots, and the code that keeps them cannot read or change what is inside.
- Which state belongs in a snapshot and which does not, and why restoring must still leave the object valid.
- What whole-state snapshots cost in memory, and the usual ways to reduce it.
The problem
Section titled “The problem”A small vector drawing editor holds shapes on a canvas, each with an id, a kind, and a position, and the canvas has a background colour. The user can also zoom and select a shape.
- FR-1 Undo and redo every change to the document: adding, moving, or removing a shape, and changing the background.
- FR-2 Zoom and selection are view settings: undo does not change them. But after an undo, the selection must not name a shape that no longer exists.
- FR-3 When the canvas gains new document state later (layers, a title, a grid size), undo must cover it without anyone remembering to update the undo code.
- C-1 (constraint) Only the canvas may change the document. The undo history must not be a back door around the canvas’s rules, such as “every shape id is unique”.
The straightforward solution
Section titled “The straightforward solution”Let the history copy what it needs from the canvas, through public getters and setters:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
namespace before {
// A canvas that lets anyone read and replace its shapes, so that a// history class outside it can save and restore them. The flaw: every// piece of state the history should save needs its own public getter// and setter, and the history has to remember to use each one.class Canvas {public: // Adds a shape and returns the id it was given (1, 2, 3, ...). int add(std::string kind, int x, int y); void set_background(Colour colour) { background_ = colour; }
// The two "doors" the history uses. shapes() hands out a read-only // reference, so nothing is copied until the history copies it. // set_shapes takes the vector by value and moves it in, replacing // every shape at once. Being public, it lets any code put in any // shapes, even two with the same id. const std::vector<Shape>& shapes() const { return shapes_; } void set_shapes(std::vector<Shape> shapes) { shapes_ = std::move(shapes); } Colour background() const { return background_; }
private: std::vector<Shape> shapes_; Colour background_ = Colour::white; // added later; History was not updated // The id the next added shape gets. It is private and has no getter, // so the history cannot save it even if it wanted to. int next_id_ = 1;};
// Keeps a stack of saved shape lists, newest at the back. It saves only// what it was written to save: the shapes. The background and next_id_// are not in a checkpoint, so undo cannot bring them back.class History {public: // Copies the canvas's current shapes onto the end of the stack. void checkpoint(const Canvas& canvas) { saved_.push_back(canvas.shapes()); } // Puts the newest saved shapes back into the canvas and forgets them. // Returns false, and changes nothing, if nothing was saved. bool undo(Canvas& canvas);
private: std::vector<std::vector<Shape>> saved_; // one whole shape list per checkpoint};
} // namespace beforeVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same edits as the real editor would make: checkpoint, then change.before::Canvas old_canvas;before::History old_history;old_history.checkpoint(old_canvas); // saves the (empty) shape listold_canvas.add("circle", 10, 10);old_history.checkpoint(old_canvas); // saves [circle]; the background is not savedold_canvas.set_background(Colour::blue);// Restores [circle], which the canvas already has. The background was// never in the checkpoint, so it stays blue: the undo did nothing useful.old_history.undo(old_canvas); // should undo the background changestd::cout << "before: undo left the background " << name(old_canvas.background()) << '\n';The first line of the output, under Check, shows the result: the background is still blue after the undo.
- The history must know every field. When the background colour was added, the history was not updated, so undo silently ignores it (FR-3 fails). Nothing in the compiler connects the two classes.
set_shapesis a public door into the canvas. Any code can now replace the shapes, including with two shapes that share an id, andnext_id_does not know (C-1 fails).- Some state is missing that the history cannot even see.
next_id_is private, so it is never saved. Here that only means ids are skipped after an undo, but the history cannot restore what it cannot read.
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(condition) records a failure// if the condition is false. They come from the site's small test header,// lld_test.hpp.// This test pins down the flaw: the history saved only the shapes, so// undoing a background change "succeeds" (returns true) but leaves the// background blue.LLD_TEST(before_history_only_restores_what_it_was_told_about) { before::Canvas canvas; before::History history; history.checkpoint(canvas); canvas.set_background(Colour::blue); LLD_CHECK(history.undo(canvas)); LLD_CHECK(canvas.background() == Colour::blue); // not undone}The pattern
Section titled “The pattern”Memento lets an object make a snapshot of its own state, which other code keeps but cannot open, and later hand the snapshot back to be restored.
Its participants:
- The originator: the object whose state is saved. It makes
snapshots and restores from them, and is the only code that knows
what they contain. Here,
Canvas. - The memento: the snapshot. To everyone except the originator, it
is an opaque value. Here,
Canvas::Snapshot. - The caretaker: keeps snapshots and decides when to save and
restore, without looking inside. Here,
History.
The originator decides what is saved; the caretaker decides when and how many. That split is what fixes the before-version: the one class that knows the fields is the one that saves them.
Text description of the diagram
A class diagram with four boxes. Canvas holds a Document, an optional selected id, and a zoom level; its functions are add, move, remove, set_background, select, set_zoom, save, which returns a Snapshot, and restore, which takes one. Snapshot holds its own Document and has one public function, shape_count. Document is a plain struct with a vector of shapes, a background colour, and the next id to hand out. History holds two vectors of snapshots, for undo and redo, and has checkpoint, undo, and redo, each taking a canvas. Filled-diamond lines show that the canvas owns its document and that each snapshot owns a copy of one. A dashed arrow from Canvas to Snapshot shows that save makes snapshots and restore reads them. A filled-diamond line from History to Snapshot shows that the history owns any number of snapshots. A dashed arrow from History to Canvas shows that the history uses a canvas only during each call, and keeps no pointer to it.
Diagram source (Mermaid)
classDiagram
class Canvas {
-Document document_
-optional~int~ selected_
-int zoom_
+add(kind, x, y) int
+move(id, dx, dy) void
+remove(id) void
+set_background(colour) void
+select(id) void
+set_zoom(percent) void
+save() Snapshot
+restore(snapshot) void
}
class Snapshot {
-Document document_
+shape_count() size_t
}
class Document {
+vector~Shape~ shapes
+Colour background
+int next_id
}
class History {
-vector~Snapshot~ undo_
-vector~Snapshot~ redo_
+checkpoint(canvas) void
+undo(canvas) bool
+redo(canvas) bool
}
Canvas *-- Document : document_
Snapshot *-- Document : a copy
Canvas ..> Snapshot : save() makes, restore() reads
History *-- "0..*" Snapshot : owns
History ..> Canvas : uses during each callThe C++ implementation
Section titled “The C++ implementation”The originator and the memento
Section titled “The originator and the memento”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The originator: a drawing made of shapes. It owns two kinds of state.// The document (shapes, background, id counter) is what undo covers. The// view (selection, zoom) is how the user is looking at it, and is never// undone. save() and restore() are the only way in or out of a snapshot.class Canvas {public: // A forward declaration: it tells the compiler "a class called // Canvas::Snapshot exists" before its body is written (below Canvas), // so that save() and restore() can already name it. class Snapshot; // the memento: only Canvas can see inside
// The document: these changes can be undone. int add(std::string kind, int x, int y); // returns the new shape's id void move(int id, int dx, int dy); // throws std::out_of_range void remove(int id); // throws std::out_of_range void set_background(Colour colour);
// The view: these are not part of the document, and are not undone. void select(int id); // throws std::out_of_range void set_zoom(int percent);
// Read-only access. shapes() returns a const reference, so callers can // look at the shapes without copying them, and cannot change them. const std::vector<Shape>& shapes() const { return document_.shapes; } Colour background() const { return document_.background; } // An empty optional means "nothing is selected". std::optional<int> selected() const { return selected_; } int zoom() const { return zoom_; }
// Makes a snapshot holding a full copy of the document. const: saving // does not change the canvas. Snapshot save() const; // Replaces the document with a copy of the one in `snapshot`. Either it // all happens or, if copying throws, nothing changes. The view is kept, // except that a selection whose shape is gone is cleared. void restore(const Snapshot& snapshot);
private: // Everything undo covers, in one struct. Saving copies the whole // struct, so a field added here later is saved and restored with no // other change. It is private: code outside Canvas cannot name it. struct Document { std::vector<Shape> shapes; Colour background = Colour::white; int next_id = 1; // always greater than every id in shapes };
// Returns a reference to the shape with this id, so move() can change // it in place. Shape& find(int id); // throws std::out_of_range
Document document_; std::optional<int> selected_; // view state: the selected shape's id, if any int zoom_ = 100; // view state, in percent};
// The memento itself: a value that holds a copy of a Document. Outside// code (the History) can store, copy, move, and hand it back, but cannot// make one or look inside, because the constructor and the data are// private. A nested class may use Canvas's private type Document, since it// is a member of Canvas. The reverse is not automatic, so `friend class// Canvas` lets Canvas call the private constructor and read document_.// There is no default constructor, so every Snapshot came from save() or// is a copy of one. The compiler-written copy and move operations are kept.class Canvas::Snapshot {public: // A harmless fact about the snapshot (for an undo menu, say) that // does not expose the document itself. std::size_t shape_count() const { return document_.shapes.size(); }
private: friend class Canvas; // explicit: a Document never turns into a Snapshot by accident. The // parameter is a copy made by the caller; std::move then hands its // contents to the member instead of copying a second time. explicit Snapshot(Document document) : document_{std::move(document)} {}
Document document_; // a copy, not a pointer: valid however the canvas changes};- All undoable state is in one private struct,
Document. Saving copies the struct, so a field added toDocumentlater is saved and restored without any other change (FR-3). The view state,selected_andzoom_, is deliberately outside it (FR-2). Snapshot’s contents are private, andCanvasis its friend. OnlyCanvascan make a snapshot or read one. The caretaker can store, copy, and hand back snapshots, and nothing else (C-1).Snapshotoffers one public query,shape_count. A memento may show harmless facts about itself, such as a size or a label for an undo menu, as long as it does not expose the state it protects.Snapshotis a value type. It holds a copy of the document, not a pointer to the canvas, so it stays valid after more edits, and even after the canvas is destroyed. Nothing ties it to the canvas that made it: it can be restored into a differentCanvas. It is copyable and movable, and moving it cannot throw (astatic_assertin the tests checks this).Snapshotis defined afterCanvas. It holds aDocumentby value, so it must be defined afterDocumentis complete. It could go insideCanvas, after the private section; defining it afterCanvaskeeps the class’s interface short.Canvasdeclaresclass Snapshot;first so thatsaveandrestorecan name it.- Access works in one direction only.
Snapshotmay use the private typeCanvas::Documentbecause a nested class is a member ofCanvas, with the same access as any other member.Canvashas no special access toSnapshot’s private members, which is whySnapshotdeclaresfriend class Canvas.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Snapshot{document_} calls the private constructor (Canvas is a friend),// which copies the whole document: every shape, the background, and the// id counter. The canvas itself is not changed.Canvas::Snapshot Canvas::save() const { return Snapshot{document_}; }
// Two steps, so that a failure cannot leave the canvas half restored:// 1. copy the snapshot's document into a local variable (this can throw,// for example std::bad_alloc, but document_ has not been touched);// 2. move the copy into document_, which cannot throw.// The snapshot is passed by const reference and is not changed, so it can// be restored again later.void Canvas::restore(const Snapshot& snapshot) { // Checked when compiling: moving a Document can never throw. If a // field is added whose move might throw, the build fails here instead // of step 2 silently losing its guarantee. static_assert(std::is_nothrow_move_assignable_v<Document>);
// Reading snapshot.document_, a private member, is allowed because // Snapshot declared Canvas its friend. Document copy = snapshot.document_; // may throw; nothing has changed yet // std::move lets document_ take over the copy's vector storage instead // of copying it again. `copy` is not used after this. document_ = std::move(copy); // cannot throw // The view is not restored, but it must still make sense. // Read left to right: if a shape is selected, and none of the restored // shapes has that id, then forget the selection. `&&` stops early when // nothing is selected, so *selected_ (the int inside the optional) is // only read when there is one. [this] lets the lambda read selected_. if (selected_ && std::ranges::none_of(document_.shapes, [this](const Shape& s) { return s.id == *selected_; })) { selected_.reset(); }}saveis a copy. It isconst: making a snapshot does not change the canvas.restorecopies first, then moves. If copying the shapes throws (for example,std::bad_alloc), the canvas is unchanged. The move intodocument_cannot throw: moving astd::vectorwith the default allocator isnoexcept, and astatic_assertinrestorechecks this for the wholeDocument. Together, that is the strong exception guarantee: a restore either happens completely or not at all.- Restoring repairs the view (FR-2). If the selected shape is not in the restored document, the selection is cleared. A memento restores the state it holds, but the originator must still make sure that everything else agrees with it.
The caretaker
Section titled “The caretaker”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The caretaker: keeps snapshots, and never looks inside them.// It owns two stacks of snapshots, each with its newest at the back:// undo_ (states to go back to) and redo_ (states that were undone). It// holds no pointer to a canvas; each call is given one by reference.class History {public: // Call before each change to the document. Clears the redo list. void checkpoint(const Canvas& canvas);
// Each returns false, and changes nothing, if there is nothing to do. // undo restores the newest snapshot on the undo list; redo restores the // newest on the redo list. Each keeps the state it replaced on the // other list, so the step can be reversed. bool undo(Canvas& canvas); bool redo(Canvas& canvas);
std::size_t snapshots() const { return undo_.size() + redo_.size(); } std::size_t shapes_held() const; // shapes copied into all snapshots
private: // The shared body of undo and redo: move one step from `from` to `to`. // static because it uses only its parameters, never this History's // members directly; undo and redo pass the lists in opposite orders. static bool step(std::vector<Canvas::Snapshot>& from, std::vector<Canvas::Snapshot>& to, Canvas& canvas);
std::vector<Canvas::Snapshot> undo_; std::vector<Canvas::Snapshot> redo_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Saves the current document, then empties the redo list: after a new// change, the old "future" no longer follows from the present. If save()// or push_back throws, undo_ is unchanged and redo_ has not been cleared.void History::checkpoint(const Canvas& canvas) { undo_.push_back(canvas.save()); redo_.clear();}
// Undo takes from undo_ and keeps the replaced state on redo_; redo is the// same step with the two lists swapped.bool History::undo(Canvas& canvas) { return step(undo_, redo_, canvas); }
bool History::redo(Canvas& canvas) { return step(redo_, undo_, canvas); }
// Restores the newest snapshot in `from` and keeps the current state in// `to`. If anything throws, the canvas and both lists are unchanged.// The order matters: everything that can throw (making room, saving,// restoring) comes before anything that changes the lists.bool History::step(std::vector<Canvas::Snapshot>& from, std::vector<Canvas::Snapshot>& to, Canvas& canvas) { if (from.empty()) { return false; // nothing to undo (or redo): change nothing } // If `to` is full, the push_back below would have to allocate, and could // throw after the canvas had already been restored. So the allocation is // done here, first. std::max<std::size_t>(1, ...) asks for at least one // slot when the capacity is 0; the <std::size_t> makes both arguments the // same type. if (to.size() == to.capacity()) { // make room, growing by doubling to.reserve(std::max<std::size_t>(1, 2 * to.capacity())); // may throw; nothing has changed yet } Canvas::Snapshot current = canvas.save(); // may throw; nothing has changed yet // from.back() is the newest snapshot. `from` and `to` are different // vectors, so reserving `to` above did not disturb it. canvas.restore(from.back()); // strong guarantee: all or nothing to.push_back(std::move(current)); // no reallocation, and the move cannot throw from.pop_back(); // the restored snapshot is now the canvas's state; drop it return true;}
// Adds up shape_count() over every snapshot on both lists. The brace list// {&undo_, &redo_} holds two pointers, so the outer loop visits each list// without copying it; *list is the list a pointer points to.std::size_t History::shapes_held() const { std::size_t total = 0; for (const auto* list : {&undo_, &redo_}) { for (const Canvas::Snapshot& snapshot : *list) { total += snapshot.shape_count(); } } return total;}How this code works: History::step, and the two lists in the Check run
step(from, to, canvas) moves one snapshot’s worth of history from one
list to the other. Undo calls it as step(undo_, redo_, canvas), redo as
step(redo_, undo_, canvas).
- Nothing to do? If
fromis empty, returnfalseat once. Nothing has been touched. - Make room in
to. Iftois full (size() == capacity()), reserve double the space (at least 1). This is the only allocation the finalpush_backcould need, so it is done now, while nothing has changed. - Save the present.
canvas.save()copies the current document intocurrent. This can throw too, and still nothing has changed. - Restore the past.
canvas.restore(from.back())copies the newest snapshot infrominto the canvas.restoreis all or nothing: if it throws, the canvas is as it was, and so are both lists. - Move the lists. Push
currentontoto(there is room, and moving a snapshot cannot throw), then pop the restored snapshot offfrom.
Steps 1 to 4 may fail but change nothing that was not put back; step 5 cannot fail. That ordering is what gives the strong guarantee.
Here are the two lists during the Check run below. “C” is the circle (id 1)
and “S” the square (id 2). Each entry in square brackets is one snapshot,
oldest first. Every snapshot on undo_ has a white background, because all
four checkpoints were made before the background turned blue.
| After | undo_ |
redo_ |
Canvas |
|---|---|---|---|
| the four edits | [no shapes] [C(10,10)] [C(10,10) S] [C(15,30) S] | empty | C(15,30) S, blue |
first undo |
[no shapes] [C(10,10)] [C(10,10) S] | [C(15,30) S, blue] | C(15,30) S, white |
second undo |
[no shapes] [C(10,10)] | [C(15,30) S, blue] [C(15,30) S, white] | C(10,10) S, white |
redo |
[no shapes] [C(10,10)] [C(10,10) S] | [C(15,30) S, blue] | C(15,30) S, white |
At the end there are 3 + 1 = 4 snapshots, holding 0 + 1 + 2 + 2 = 5 shapes, which is the last line of the output. The zoom (150) is in none of them.
checkpointis called before each change, not after: the snapshot holds the state the change is about to replace. A new change also clears the redo list, since redoing an old future on top of a new change makes no sense.- Undo and redo are one function,
step, with the lists swapped. Undo saves the current state on the redo list and restores the newest undo snapshot; redo does the reverse. stepkeeps the strong guarantee too. It makes room intofirst, if needed, then saves the current state, both before anything changes. It growstoby doubling, becausereserve(size() + 1)may allocate exactly one more slot each time, and a run of undos would then reallocate on every step. Then it restores, which is all or nothing. The finalpush_backcannot fail: the room is already there, and moving a snapshot cannot throw. If any step throws, the canvas and both lists are as they were, and the user can simply try again.- The history keeps no pointer to the canvas. Each call takes the canvas by reference for the length of the call, so there is no lifetime to manage between them.
class Canvas
the originator: owns the document and the view
Data members
Document document_;shapes, background, next_id: everything undo coversstd::optional<int> selected_;view: not undoneint zoom_;view: not undone
Member functions
int add(std::string kind, int x, int y);returns the new idvoid move(int id, int dx, int dy);throws std::out_of_rangevoid remove(int id);throws std::out_of_rangevoid set_background(Colour colour);void select(int id);throws std::out_of_rangevoid set_zoom(int percent);Snapshot save() const;void restore(const Snapshot& snapshot);strong guarantee; clears a stale selection
class Canvas::Snapshot
the memento: an opaque value; Canvas is a friend
Data members
explicit Snapshot(Document document);private: only Canvas can make oneDocument document_;a copy
Member functions
std::size_t shape_count() const;the only public query
class History
the caretaker: never looks inside a snapshot
Data members
std::vector<Canvas::Snapshot> undo_;std::vector<Canvas::Snapshot> redo_;
Member functions
void checkpoint(const Canvas& canvas);before each change; clears redobool undo(Canvas& canvas);false if there is nothing to undobool redo(Canvas& canvas);false if there is nothing to redostd::size_t snapshots() const;std::size_t shapes_held() const;
The outline leaves out the read-only getters (shapes, background,
selected, zoom), Canvas::find, History::step, and the
Document and Shape structs.
Following one undo
Section titled “Following one undo”Text description of the diagram
A sequence diagram with three participants: the editor code, History, and Canvas. The editor calls undo on the history, passing the canvas. The history first reserves room in its redo list. It calls save on the canvas, which returns a snapshot of the current document. It then calls restore on the canvas with the newest snapshot in its undo list. The canvas copies that snapshot’s document and moves the copy into its own, then clears its selection if the selected shape no longer exists. Back in the history, the saved snapshot is pushed onto the redo list and the newest undo snapshot is removed. undo returns true to the editor.
Diagram source (Mermaid)
sequenceDiagram
participant Editor as editor code
participant History
participant Canvas
Editor->>History: undo(canvas)
History->>History: reserve room in redo_
History->>Canvas: save()
Canvas-->>History: snapshot of the current document
History->>Canvas: restore(newest in undo_)
Canvas->>Canvas: copy, then move into document_
Canvas->>Canvas: clear the selection if its shape is gone
History->>History: push the saved snapshot onto redo_
History->>History: pop the newest from undo_
History-->>Editor: trueVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Canvas canvas;History history;
// The rule for the editor code: call checkpoint just BEFORE each// change to the document, so the snapshot holds the state that the// change is about to replace. Four changes, four checkpoints.history.checkpoint(canvas); // snapshot 1: no shapesconst int circle = canvas.add("circle", 10, 10); // the circle gets id 1history.checkpoint(canvas); // snapshot 2: the circlecanvas.add("square", 40, 10); // id 2history.checkpoint(canvas); // snapshot 3: circle and squarecanvas.move(circle, 5, 20); // the circle goes to (15, 30)history.checkpoint(canvas); // snapshot 4: moved circle, whitecanvas.set_background(Colour::blue);canvas.set_zoom(150); // view only: no checkpointshow("edited", canvas);
// Each undo puts back the newest snapshot (first 4, then 3), and keeps// the state it replaced on the redo list. redo then steps forward one.// The bool results say whether there was anything to do; this demo// knows there was, so it ignores them.history.undo(canvas); // back to snapshot 4: white againshow("undo", canvas);history.undo(canvas); // back to snapshot 3: the circle at (10, 10)show("undo", canvas);history.redo(canvas); // forward again: the circle at (15, 30), still whiteshow("redo", canvas);// snapshots(): 3 on the undo list + 1 on the redo list.std::cout << "history: " << history.snapshots() << " snapshots holding " << history.shapes_held() << " shape copies\n";before: undo left the background blueedited: circle#1 at (15,30) square#2 at (40,10); blue; zoom 150undo: circle#1 at (15,30) square#2 at (40,10); white; zoom 150undo: circle#1 at (10,10) square#2 at (40,10); white; zoom 150redo: circle#1 at (15,30) square#2 at (40,10); white; zoom 150history: 4 snapshots holding 5 shape copiesRead the output against the requirements:
- The first undo turns the background white again (FR-1): the change the before-version could not undo. The circle is still at (15, 30), because that was an earlier change.
- The second undo moves the circle back to (10, 10); redo moves it to (15, 30) again, with the background still white, because the background change is now one step further forward on the redo list.
- The zoom stays at 150 throughout (FR-2). It is view state and was never in a snapshot.
4 snapshots holding 5 shape copies. Three on the undo list (holding 0, 1, and 2 shapes) and one on the redo list (2 shapes). Each snapshot holds a whole copy of the document, which is the cost discussed below.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_CHECK_EQ(actual, expected) fails, and prints both values, unless they// are equal. LLD_CHECK_THROWS(expression, type) fails unless the expression// throws that type of exception. Both come from lld_test.hpp.//// These three are checked by the compiler, not at run time. A snapshot can// be copied (a history may keep copies); it cannot be made from nothing,// only by Canvas::save; and moving one cannot throw, which History::step// relies on for its final push_back.static_assert(std::is_copy_constructible_v<Canvas::Snapshot>);static_assert(!std::is_default_constructible_v<Canvas::Snapshot>);static_assert(std::is_nothrow_move_constructible_v<Canvas::Snapshot>);
// Save with one circle at (1, 2), then change three things: move it, turn// the background blue, add a square. One restore undoes all three.LLD_TEST(restoring_a_snapshot_brings_back_the_whole_document) { Canvas canvas; const int id = canvas.add("circle", 1, 2); const Canvas::Snapshot saved = canvas.save(); canvas.move(id, 10, 10); canvas.set_background(Colour::blue); canvas.add("square", 0, 0); canvas.restore(saved); LLD_CHECK_EQ(canvas.shapes().size(), std::size_t{1}); LLD_CHECK_EQ(canvas.shapes()[0].x, 1); LLD_CHECK(canvas.background() == Colour::white);}
// The snapshot is taken before any shape exists, so it holds next_id = 1.// Restoring it resets the counter too, and the next shape gets id 1 again.LLD_TEST(the_id_counter_is_part_of_the_snapshot) { Canvas canvas; const Canvas::Snapshot empty = canvas.save(); const int first = canvas.add("circle", 0, 0); canvas.restore(empty); const int second = canvas.add("square", 0, 0); LLD_CHECK_EQ(first, 1); LLD_CHECK_EQ(second, 1); // the id was freed with the shape, so reusing it is safe}
// Adds and selects a shape, and zooms, after the checkpoint. Undo removes// the shape; the zoom (view state) stays at 200, and the selection, which// would now name a missing shape, is cleared.LLD_TEST(the_view_is_not_undone_but_stays_valid) { Canvas canvas; History history; history.checkpoint(canvas); const int id = canvas.add("circle", 0, 0); canvas.select(id); canvas.set_zoom(200); LLD_CHECK(history.undo(canvas)); LLD_CHECK_EQ(canvas.zoom(), 200); LLD_CHECK(!canvas.selected().has_value()); // the selected shape is gone}
// One change, then: undo works once, a second undo has nothing to do and// returns false; redo works once, a second redo returns false.LLD_TEST(undo_and_redo_walk_back_and_forward) { Canvas canvas; History history; history.checkpoint(canvas); canvas.add("circle", 0, 0); LLD_CHECK(history.undo(canvas)); LLD_CHECK(canvas.shapes().empty()); LLD_CHECK(!history.undo(canvas)); LLD_CHECK(history.redo(canvas)); LLD_CHECK_EQ(canvas.shapes().size(), std::size_t{1}); LLD_CHECK(!history.redo(canvas));}
// After an undo there is something to redo, but a new checkpoint (made// before a new change) throws that redo state away.LLD_TEST(a_new_change_clears_redo) { Canvas canvas; History history; history.checkpoint(canvas); canvas.add("circle", 0, 0); history.undo(canvas); history.checkpoint(canvas); canvas.set_background(Colour::blue); LLD_CHECK(!history.redo(canvas));}
// No shape has id 7 on an empty canvas, so each call must throw// std::out_of_range rather than quietly do nothing.LLD_TEST(a_missing_shape_is_refused) { Canvas canvas; LLD_CHECK_THROWS(canvas.move(7, 1, 1), std::out_of_range); LLD_CHECK_THROWS(canvas.remove(7), std::out_of_range); LLD_CHECK_THROWS(canvas.select(7), std::out_of_range);}the_view_is_not_undone_but_stays_validundoes the adding of a selected shape: the zoom stays, and the selection is cleared.the_id_counter_is_part_of_the_snapshotshows thatnext_idcomes back with the document. After undoing the only add, id 1 is free again, and the next shape gets it. The old shape 1 is gone from the document, and the next checkpoint clears the redo list, so nothing in the canvas or the history refers to it. Code outside that kept id 1 would now name the new shape. If that matters, keep the counter outsideDocument, so that it only grows; ids stay unique either way.a_new_change_clears_redochecks that there is no redo after a new change.
What it costs
Section titled “What it costs”Every snapshot here is a whole copy of the document. With s shapes and h undo steps, the history holds about s × h shapes. For a canvas of a few hundred shapes and a hundred undo steps, that is tens of thousands of small structs, which most programs can afford. For a large image, a long text, or a game world, it may not be.
The usual ways to reduce it:
| Approach | Saves memory by | Costs |
|---|---|---|
| Limit the history to the last N steps (see the exercise) | forgetting old snapshots | the user cannot undo past N |
| Record changes instead of states: Command | storing only what each step changed | every change needs a correct reverse |
Share unchanged parts between snapshots, for example holding std::shared_ptr<const Shape> |
copying pointers, not shapes, for what did not change | more complex code; every shared part must be immutable |
| Save only part of the state that a step can change | smaller snapshots | the originator must know which part each step touches |
None of these is measured here: the example counts shape copies, not bytes. Measure the real program before deciding that snapshots are too expensive.
Memento or Command?
Section titled “Memento or Command?”| Question | Memento | Command |
|---|---|---|
| What is stored per step? | the whole state (or a large part of it) | what the step did, and how to reverse it |
| What must each change provide? | nothing: call checkpoint before it |
a correct undo, for every kind of change |
| A change that is hard to reverse | easy: the old state is just restored | hard: the command must save what it destroys |
| Large state, small changes | expensive | cheap |
| Knowing what each step did | not by itself; the caller must supply a label (see below) | yes: “moved circle 1”, for an undo menu |
They combine well: a command that cannot reverse its change, such as a filter applied to an image, can keep a memento of the part it changed.
When to use it
Section titled “When to use it”- An object’s state must be saved and restored: undo, “revert”, checkpoints, cancelling a dialog, rolling back after a failed step.
- The state is private, and should stay so: you do not want getters and setters for everything just so that a history class can copy it.
- The state is small enough to copy, or can be shared cheaply, as measured in the program you have.
When not to use it
Section titled “When not to use it”- The state is already a public value. If a
struct Settingsis meant to be read and written by anyone, keep a copy of it: that is a memento without the ceremony. - The state is large and the changes are small. Record the changes instead (Command).
- The state includes things you cannot copy: open files, network connections, other threads. A snapshot of a file handle does not restore the file. Save a description of such things (a path, an address) and reopen them, or leave them out of the snapshot.
- The state is shared with other objects. Restoring one object’s snapshot can leave others out of step with it. Snapshot all of them together, or rethink who owns that state.
- Memory, as above: whole copies add up.
- The originator must decide what is document and what is view. Getting it wrong either undoes too much (undo changes the zoom) or too little (undo misses a field).
- Restoring must keep the object valid. Everything that is not in the snapshot must still agree with what is, like the selection here.
- The caretaker must save at the right moments. A change made without a
checkpointbefore it merges into the previous step. And a checkpoint whose change then fails (for example,movethrowsstd::out_of_rangefor an unknown id) leaves an undo step that does nothing, and has already cleared redo. If changes can fail, save first and keep the snapshot only on success: takecanvas.save(), make the change, then hand the snapshot to the history.
Common misuse
Section titled “Common misuse”- Getters and setters “for the history”. A public
set_statewith everything in it is not a memento; it is a public door into the object (the before-version). - A memento that holds pointers into the originator. A snapshot of
std::vector<Shape*>points at the shapes that will change next, or that may already be destroyed (afterremove, or when the vector reallocates). Restoring it brings back their current values at best, and dangling pointers at worst. Copy values, or share only immutable ones. - Saving the view with the document. Undo then jumps the zoom and selection around with every step.
- Restoring with a weaker guarantee than you think. Assigning a
large structure in place can fail halfway on some types. Copy first,
then move or swap, as
restoredoes.
When the requirements change
Section titled “When the requirements change”- “Add layers.” Add
std::vector<Layer>toDocument. Saving and restoring cover it with no other change (FR-3). - “Show the undo history as a list: ‘Move circle’, ‘Change
background’.” Store a label with each snapshot in
History, given by the caller ofcheckpoint. The snapshot itself does not need to change. - “Save the document to a file.” A snapshot is not a file format.
Write a separate save function, with a versioned format, so that old
files still open after
Documentchanges. - “Undo used too much memory on large drawings.” Limit the history, or share unchanged shapes between snapshots; see the table above.
Exercise
Section titled “Exercise”Exercise: Limit the history size
Change History so that it keeps at most N undo steps, given when it
is constructed. When a new checkpoint would make the history hold more
than N, the oldest one is forgotten.
- Which container would you use for the undo list, and why?
- Write the new
checkpoint, and keepundoandredoworking. Explain whetherundostill has the strong exception guarantee. - What should happen if N is 0?
- After five changes with N = 3, the user presses undo until it stops. How many shapes are left, if each change added one?
Show the explained answer
1. std::deque: it can remove the oldest element from the front in
constant time, and add to the back. A std::vector would have to shift
every snapshot along with erase(begin()), which moves every remaining snapshot each time: cheap moves, but O(N) per checkpoint. (A fixed-size ring buffer, like the one on the
Iterator page, would also work.)
2.
// A history that keeps at most `limit` undo snapshots. std::deque (a// double-ended queue) can drop the oldest snapshot from the front cheaply.class History {public: // Refuses a limit of 0: a history that can keep nothing is a mistake. explicit History(std::size_t limit) : limit_{limit} { if (limit == 0) { throw std::invalid_argument("a history must keep at least one snapshot"); } }
// Save first; only then, if the list has grown past the limit, forget // the oldest. The list is never longer than limit_ after this returns. void checkpoint(const Canvas& canvas) { undo_.push_back(canvas.save()); if (undo_.size() > limit_) { undo_.pop_front(); // forget the oldest } redo_.clear(); }
bool undo(Canvas& canvas) { return step(undo_, redo_, canvas); } bool redo(Canvas& canvas) { return step(redo_, undo_, canvas); }
private: // The same job as the example's step, without reserve (a deque has // none). It pushes the current state first, and undoes that push if // the restore throws, so a failure still changes nothing. static bool step(std::deque<Canvas::Snapshot>& from, std::deque<Canvas::Snapshot>& to, Canvas& canvas) { if (from.empty()) { return false; } to.push_back(canvas.save()); // may throw; nothing else has changed try { canvas.restore(from.back()); } catch (...) { // `...` catches an exception of any type to.pop_back(); // put `to` back as it was throw; // a bare `throw;` passes the same exception on to the caller } from.pop_back(); return true; }
std::size_t limit_; std::deque<Canvas::Snapshot> undo_; std::deque<Canvas::Snapshot> redo_;};std::deque has no reserve, so the trick in the example (make room
first, so the last push_back cannot fail) is not available. Instead,
step pushes the current state first, and takes it off again if the
restore throws. pop_back cannot throw, so the strong guarantee still
holds. The redo list is not limited here: it can only hold what was
undone, which is at most N steps.
3. A history that keeps nothing cannot undo anything. Either refuse it, as above, or accept it as “undo is off” and document that. What you should not do is accept 0 and then keep one anyway.
4. Two. The first two checkpoints were forgotten, so three undos remove the last three shapes, and the first two stay. A scratch program built on the example’s canvas printed “undo steps kept: 3” and “undone 3, shapes left 2”.
Related patterns
Section titled “Related patterns”- Command builds undo from changes instead of states, and the two combine; see Memento or Command? and Command.
- Prototype also copies an object, but to make a new one, not to restore an old state. See Prototype.
- Iterator’s ring buffer is a natural container for a history with a fixed limit. See Iterator.
Summary
Section titled “Summary”- Memento saves an object’s state as an opaque value that others keep but cannot open, so the object can be restored without exposing its internals.
- The originator decides what is saved; the caretaker decides when and how many.
- In C++, a nested snapshot class with private contents and the originator as a friend gives exactly that access. Keep the undoable state in one struct, so a new field is saved automatically.
- Keep view state out of the snapshot, and make restore leave the object valid, with the strong exception guarantee when you can.
- Whole copies cost memory. Limit the history, share unchanged parts, or record changes with Command when the state is large.