Flyweight
What you will learn on this page
Section titled “What you will learn on this page”- What the Flyweight pattern is for: holding very many objects that are mostly the same, without paying for the same data again and again.
- How to split an object’s state into intrinsic state, which is the same wherever the object appears and can be shared, and extrinsic state, which belongs to one place and must stay outside the shared object.
- How to write the shared objects and the cache that makes them in C++: immutable objects, a container whose elements never move, and observer pointers whose lifetime depends on the cache.
- When the savings are real, how to tell, and when the pattern is not worth its cost.
The problem
Section titled “The problem”A text editor lays out documents for display. Each character on the page is drawn from a glyph: the shape of that character in one font at one size. Making a glyph is slow (a font library draws it) and it is large: here, one byte per pixel of a square as tall as the font size.
- FR-1 Lay out lines of text in a given style (font, size, colour), placing each character after the previous one.
- FR-2 Every character on the page has its own position and colour; one character can be highlighted without changing any other.
- FR-3 Documents of hundreds of thousands of characters must fit in memory.
- C-1 (constraint) A font library is slow to call; ask it for each shape as few times as possible.
Most documents use a few dozen different characters, in one or two fonts and sizes.
The straightforward solution
Section titled “The straightforward solution”Each character carries everything needed to draw it:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every character carries everything needed to draw it. A Character is a// plain value: copying one copies all of it, including its own mask, and// changing one never affects another. Nothing is shared, so nothing can go// wrong between characters; the cost is that identical data is repeated.struct Character { char character; // which letter, digit, or space this is std::string font; // the font name, repeated in every character of the line int size; // the size in pixels, also repeated std::vector<std::uint8_t> mask; // size x size bytes, for every character int width; // how far the pen moves after this character int x; // where this character starts across the line int y; // where its line is down the page Colour colour;};
// A document laid out the straightforward way: a list of lines, each a list// of full Character values. It owns all of them by value.class Document {public: // Lays out `text` as a new line below the previous one, in `style`. // Calls the font library (rasterise) once for EVERY character, even if // the same letter was drawn a moment ago. If `text` is not empty and the // style has an empty font or a size outside 1..128, rasterise throws // std::invalid_argument and the document is left unchanged. void add_line(std::string_view text, const Style& style); // Changes the colour of one character only. `line` and `column` count // from 0. void highlight(std::size_t line, std::size_t column, Colour colour); // throws std::out_of_range
const Character& at(std::size_t line, std::size_t column) const; // throws std::out_of_range std::size_t characters() const; // how many characters, over all lines std::size_t mask_bytes() const; // the bytes held in all the masks added together
private: // The outer vector is the lines, top to bottom; each inner vector is one // line's characters, left to right. lines_[2][5] is line 2, column 5. std::vector<std::vector<Character>> lines_; int next_y_ = 0; // the y position the next line will get};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Builds one line of characters, left to right, then adds it to the end of// the document. The line is built in a local vector first, so if rasterise// throws part-way, the document is left exactly as it was.void Document::add_line(std::string_view text, const Style& style) { std::vector<Character> line; int x = 0; // the pen starts at the left edge for (const char character : text) { // one pass per character, spaces included const int width = advance(character, style.size); // The braces build a Character field by field, in the order the // struct declares them. Two things are paid again for every // character: style.font is copied into a new std::string, and // rasterise makes a brand-new size x size mask (256 bytes at size // 16), even for a letter this line has already used. line.push_back({character, style.font, style.size, rasterise(character, style.font, style.size), width, x, next_y_, style.colour}); x += width; // the next character starts where this one ends } // std::move hands the finished line's storage over to lines_ instead of // copying every Character; `line` is not used again. lines_.push_back(std::move(line)); next_y_ += style.size + 4; // the next line goes below: this size plus a 4-pixel gap}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 50 lines of "the cat sat on the mat" (22 characters each, spaces// included) in Mono 16, then "THE END" (7 characters) in Mono 24.before::Document doc;for (int i = 0; i < 50; ++i) { doc.add_line(text, body);}doc.add_line("THE END", heading);// Every character holds its own mask, so the number of masks is// simply the number of characters: doc.characters() is printed twice.std::cout << "before: " << doc.characters() << " characters, " << doc.characters() << " masks, " << doc.mask_bytes() << " mask bytes\n";This is simple and correct. Each character is a plain value, and highlighting one changes only that one. For a short label, it is the right design. For a document, it strains FR-3 (roughly 340 bytes per character before heap overhead, so a few hundred thousand characters need around 100 MB just for layout) and fails C-1:
- Every character holds its own mask. The fifty lines of “the cat sat on the mat” contain 1100 characters but only 10 different ones, and each of the 1100 has its own 256-byte mask.
- The font library is called for every character, 1107 times, where 16 calls would do.
- Each character also repeats its font name and size, which are the same along the whole line.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records a// failure, and prints both values, if they are not equal. They come from the// site's small test header, lld_test.hpp. `body` is Mono at size 16.// The test: four identical letters still make four masks of 16 x 16 bytes// each, because nothing is shared.LLD_TEST(before_every_character_holds_its_own_mask) { before::Document doc; doc.add_line("aaaa", body); LLD_CHECK_EQ(doc.characters(), std::size_t{4}); LLD_CHECK_EQ(doc.mask_bytes(), std::size_t{4 * 16 * 16});}Step 1: sort the data
Section titled “Step 1: sort the data”The pattern starts with one question for each piece of data: is it the same wherever this character appears, or does it belong to one place on the page?
| Data | Same for every t in this font and size? |
Kind |
|---|---|---|
| the character | yes | intrinsic: share it |
| the font and size | yes (they are part of what makes the shape) | intrinsic: share it |
| the mask (the shape) | yes | intrinsic: share it |
| the width (how far to move after it) | yes | intrinsic: share it |
| the position, x and y | no: every t is somewhere else |
extrinsic: keep it per place |
| the colour | no: FR-2 lets one t be highlighted |
extrinsic: keep it per place |
Intrinsic state is the same wherever the object is used, so one copy can serve every use. Extrinsic state depends on where it is used, so it must stay with each use, or be passed in when needed.
The colour row is the one to get right. Colour looks like part of how a
character is drawn, but FR-2 says it differs from one place to the next.
If it went into the shared glyph, highlighting one t would colour
every t in the document.
The pattern
Section titled “The pattern”Flyweight shares one object among all the places that need the same intrinsic state, and keeps the extrinsic state outside it. A factory makes each shared object once and hands it out to everyone who asks for the same key.
Its participants:
- The flyweight: the shared object, holding only intrinsic state.
It must not change once made. Here,
Glyph. - The flyweight factory: makes flyweights on first request, keeps
them, and returns the same one for the same key. Here,
GlyphCache. - The client: keeps the extrinsic state, and a reference to the
flyweight, for each use. Here,
Document, throughPlacedGlyph.
Text description of the diagram
A class diagram with four classes. Glyph holds a key, a width, and a vector of bytes for its mask, and has functions to read each of them; it has no functions that change it. GlyphCache holds a map from glyph keys to glyphs, and has get, which takes a character, a font, and a size and returns a constant reference to a glyph, plus size and mask_bytes. PlacedGlyph is a struct with a pointer to a constant Glyph, x and y positions, and a colour. Document holds a pointer to a GlyphCache and a vector of lines, each a vector of PlacedGlyph, and has add_line, highlight, at, and characters. Filled-diamond composition lines show that the cache owns any number of glyphs and that the document owns its placed glyphs. A plain arrow from PlacedGlyph to Glyph shows that each placed glyph observes a shared glyph without owning it, and a plain arrow from Document to GlyphCache shows that the document borrows the cache.
Diagram source (Mermaid)
classDiagram
class Glyph {
-GlyphKey key_
-int width_
-vector~uint8_t~ mask_
+key() const GlyphKey&
+width() int
+mask() span~const uint8_t~
}
class GlyphCache {
-map~GlyphKey, Glyph~ glyphs_
+get(character, font, size) const Glyph&
+size() size_t
+mask_bytes() size_t
}
class PlacedGlyph {
+const Glyph* glyph
+int x
+int y
+Colour colour
}
class Document {
-GlyphCache* cache_
-vector~vector~PlacedGlyph~~ lines_
+add_line(text, style) void
+highlight(line, column, colour) void
+at(line, column) const PlacedGlyph&
+characters() size_t
}
GlyphCache *-- "0..*" Glyph : glyphs_ (owns)
Document *-- "0..*" PlacedGlyph : lines_ (owns)
PlacedGlyph --> Glyph : glyph (observes)
Document --> GlyphCache : cache_ (borrows)For “the cat”, the objects look like this: two PlacedGlyphs for the
two ts, each with its own position, pointing at one Glyph.
Text description of the diagram
A diagram of objects in two groups. The Document group holds six placed characters from the words “the cat”, leaving out the space: t at x 0, h at x 8, e at x 16, c at x 28, a at x 36, and t at x 44. The GlyphCache group holds five glyphs, all in font Mono at size 16: t, h, e, c, and a. Each placed character has an arrow to the glyph for its letter. The two t’s, at x 0 and x 44, both point at the same t glyph, which is held once.
Diagram source (Mermaid)
flowchart LR
subgraph Document
P1["t at x 0"]
P2["h at x 8"]
P3["e at x 16"]
P5["c at x 28"]
P6["a at x 36"]
P7["t at x 44"]
end
subgraph GlyphCache
T["Glyph t, Mono 16"]
H["Glyph h, Mono 16"]
E["Glyph e, Mono 16"]
C["Glyph c, Mono 16"]
A["Glyph a, Mono 16"]
end
P1 -->|points at| T
P7 -->|points at| T
P2 --> H
P3 --> E
P5 --> C
P6 --> AThe C++ implementation
Section titled “The C++ implementation”The flyweight: Glyph
Section titled “The flyweight: Glyph”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What identifies a glyph: the same three values always give the same shape.// Two keys are equal when all three fields are equal; ('a', "Mono", 16) and// ('a', "Mono", 24) are different keys, so different glyphs.struct GlyphKey { char character; std::string font; int size; // `= default` asks the compiler to write the comparisons (C++20's // "spaceship" operator): it compares character first, then font, then // size, and the first field that differs decides. std::map needs this // "less than" to keep its keys in order. auto operator<=>(const GlyphKey&) const = default;};
// The flyweight: the shape of one character in one font and size.// Immutable, so one glyph can be shared by every place it appears.// Everything in it is intrinsic state: the same wherever this letter is// drawn. Where it is drawn and in what colour live outside it, in the// document. `final` means no class can derive from Glyph.class Glyph final {public: // Works out the width and the mask from the key, once. Throws // std::invalid_argument (from rasterise) for an empty font or a size // outside 1..128, so a Glyph that exists always has a valid mask. // `explicit` stops a GlyphKey from silently turning into a Glyph. explicit Glyph(GlyphKey key); // rasterises; throws for bad input // Copying is switched off (`= delete`): a copy would be a second glyph // with the same key and its own mask, the very waste being avoided. // Because copy operations are declared, no move operations are made // either, so a Glyph stays where it was built. Glyph(const Glyph&) = delete; Glyph& operator=(const Glyph&) = delete;
// Read-only access only: every function is const and there are no // setters, so no user of a shared glyph can change what others see. const GlyphKey& key() const { return key_; } int width() const { return width_; } // std::span is a read-only view of the bytes: it lets a caller look at // the mask without copying it. It points into this glyph, so it is only // valid while the glyph exists. std::span<const std::uint8_t> mask() const { return mask_; }
private: GlyphKey key_; int width_; // how far the pen moves after this character std::vector<std::uint8_t> mask_; // size x size bytes};- The key says what makes two glyphs the same: character, font,
and size. The defaulted
operator<=>(C++20) compares the three in order, which is whatstd::mapneeds to sort keys. - A
Glyphcannot change after it is made. Every accessor isconst, and there are no setters. This is what makes sharing safe: no user of a glyph can change what another user sees. It also makes sharing between threads safe for reading, once a glyph exists. - Copying is deleted. A copy would be a second glyph with the same
key, which is the waste the pattern exists to avoid. It also stops a
caller from writing
Glyph g = cache.get(...)by mistake, copying a mask into every character.
The flyweight factory: GlyphCache
Section titled “The flyweight factory: GlyphCache”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The flyweight factory: makes each glyph once, and hands out references.// It owns every Glyph it makes; callers only borrow them. Its job is to// make sure there is never more than one Glyph for the same key.class GlyphCache {public: GlyphCache() = default; // Not copyable: documents point at the glyphs inside one particular // cache, and a copy would hold different glyph objects for the same keys. GlyphCache(const GlyphCache&) = delete; GlyphCache& operator=(const GlyphCache&) = delete;
// Returns the one glyph for (character, font, size), making it on the // first request. Later requests for the same three values return the // same object. Throws std::invalid_argument, and adds nothing, if the // glyph cannot be made (empty font, size outside 1..128). // Valid for as long as the cache lives. const Glyph& get(char character, const std::string& font, int size);
std::size_t size() const { return glyphs_.size(); } // how many different glyphs exist std::size_t mask_bytes() const; // bytes in all the glyphs' masks, each counted once
private: // Sorted by GlyphKey, using the operator<=> above. Each element lives // in its own separately allocated node. std::map<GlyphKey, Glyph> glyphs_; // a node-based map: adding never moves a glyph};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Look first, make only if missing. The search and the insert each take// time that grows with the logarithm of the number of glyphs (std::map is// a sorted tree), which stays small: a document has a few dozen glyphs.const Glyph& GlyphCache::get(char character, const std::string& font, int size) { GlyphKey key{character, font, size}; // copies `font` into the key // find returns an iterator: a position in the map. If the key is not // there, it returns glyphs_.end(), a "one past the last" position that // means "not found". const auto found = glyphs_.find(key); if (found != glyphs_.end()) { // A map element is a pair: `first` is the key, `second` the Glyph. // Hand back the glyph that is already there: no new work. return found->second; } // Made only on the first request; if rasterising throws, nothing is added. // try_emplace(key, key): the first `key` is the map key (copied in); // the second is passed to Glyph's constructor, which builds the glyph // directly inside the map's node, as a Glyph cannot be copied or moved // there. It returns a pair (position, inserted?); `.first->second` is // the glyph at that position. return glyphs_.try_emplace(key, key).first->second;}getmakes a glyph only on the first request (C-1). Later requests for the same key find it and return the same object.try_emplace(key, key)builds theGlyphin place, inside the map. AGlyphcannot be copied, and since it declares copy operations, the compiler does not generate move operations, and a move would fall back to the deleted copy. So it must be constructed where it will live. If rasterising throws, nothing is added.- The container choice is part of the design. The cache hands out
references, so the glyphs must never move.
std::mapis node-based: adding an element never moves the others, so a reference stays valid as long as the element stays in the map. (std::unordered_mapalso keeps references to its elements valid when it grows, though not its iterators.) Astd::vector<Glyph>would not even compile here, because growing it must move or copy elements; for a movable type, growing it relocates them, and every reference handed out before would dangle. - The cache cannot be copied. Documents point into one particular cache; a copy would hold different glyph objects with the same keys.
The client: Document and PlacedGlyph
Section titled “The client: Document and PlacedGlyph”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One character on the page: the shared glyph, and what is particular// to this place (the extrinsic state).// A PlacedGlyph is small: one pointer, two ints, and a colour, and no mask.// Many PlacedGlyphs can point at the same Glyph.struct PlacedGlyph { // A pointer that only looks, never owns: deleting a PlacedGlyph does not // delete the glyph. `const Glyph*` means the glyph cannot be changed // through this pointer. It stays valid while the cache lives, because // the cache never moves or removes a glyph. const Glyph* glyph; // observer: owned by the cache int x; // where this character starts across the line int y; // where its line is down the page Colour colour; // this place's colour; highlighting changes only this};
// The client of the flyweights: it keeps each character's place and asks the// cache for the shared shape. It owns its PlacedGlyphs, but not the glyphs// they point at, and not the cache.class Document {public: // Stores the cache's address (`&cache`), so every line this document // lays out uses that one cache. explicit Document(GlyphCache& cache) : cache_{&cache} {}
// Lays out `text` as a new line below the previous one. If `text` is // not empty and the style's font is empty or its size is outside 1..128, // the cache throws std::invalid_argument on the first character, and // the document is left unchanged. void add_line(std::string_view text, const Style& style); // Recolours one place on the page; the shared glyph is not touched. void highlight(std::size_t line, std::size_t column, Colour colour); // throws std::out_of_range
const PlacedGlyph& at(std::size_t line, std::size_t column) const; // throws std::out_of_range std::size_t characters() const; // how many characters, over all lines
private: // Stored as a pointer, not a reference: a reference member would stop // one Document being assigned to another. It is never null, because the // constructor takes a reference. GlyphCache* cache_; // borrowed: must outlive the document // Lines top to bottom; each inner vector is one line, left to right. std::vector<std::vector<PlacedGlyph>> lines_; int next_y_ = 0; // the y position the next line will get};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same layout as the before-version, with one change: instead of making// a mask for every character, it asks the cache for the shared glyph and// keeps only a pointer to it, plus this place's position and colour.void Document::add_line(std::string_view text, const Style& style) { std::vector<PlacedGlyph> line; // built here first, added to lines_ at the end int x = 0; // the pen starts at the left edge for (const char character : text) { // The intrinsic state comes from the cache: the first 't' in this // font and size makes the glyph, every later 't' gets the same one. // A reference (`const Glyph&`), so the glyph is not copied. const Glyph& glyph = cache_->get(character, style.font, style.size); // The extrinsic state is worked out here, by the client: the glyph's // address (&glyph), where it goes (x, next_y_), and its colour. line.push_back({&glyph, x, next_y_, style.colour}); x += glyph.width(); // the shared glyph says how far to move the pen } // std::move hands the finished line's storage to lines_ instead of // copying it. The pointers inside stay valid: they point into the // cache, not into `line`. lines_.push_back(std::move(line)); next_y_ += style.size + 4; // the next line goes below: this size plus a 4-pixel gap}How this code works: Laying out a line with shared glyphs
Document::add_line and GlyphCache::get work together. For each
character of the text:
- Ask the cache.
getbuilds aGlyphKeyfrom the character, the font, and the size, and looks it up withfind. - Found: it returns a reference to the glyph already in the map. Nothing is made, and the font library is not called.
- Not found:
try_emplacebuilds a newGlyphinside the map, which callsrasteriseto make its mask. If that throws, the map is unchanged and the exception leavesgetandadd_line. The new line was only a local vector, so the document is unchanged too. - Record the place. The document stores the glyph’s address, the
current
x, the line’sy, and the style’s colour in aPlacedGlyph. - Move the pen right by the glyph’s width: half the size for a letter, a quarter for a space.
Here are the first eight characters of the first line, “the cat sat on
the mat”, in Mono 16 (y is 0 for all of them):
| Column | Character | Cache | Glyphs in cache | x |
Width |
|---|---|---|---|---|---|
| 0 | t |
made | 1 | 0 | 8 |
| 1 | h |
made | 2 | 8 | 8 |
| 2 | e |
made | 3 | 16 | 8 |
| 3 | space | made | 4 | 24 | 4 |
| 4 | c |
made | 5 | 28 | 8 |
| 5 | a |
made | 6 | 36 | 8 |
| 6 | t |
found | 6 | 44 | 8 |
| 7 | space | found | 6 | 52 | 4 |
By the end of the first line the cache holds all 10 different
characters. Each of the other 49 lines of the same text finds every glyph, so it makes
none; it only adds small PlacedGlyph values, with y 20 for line 1,
40 for line 2, and so on (each line is the size plus 4 pixels lower).
Who owns what. The cache owns every Glyph. The document owns its
lines and their PlacedGlyph values, but each of those only points at a
glyph it does not own. That is why the cache must be created before the
document and outlive it, and why the cache must never move a glyph once
it has handed out its address.
PlacedGlyphholds only the extrinsic state, x, y, and colour, plus a pointer to the shared glyph. It is small: 24 bytes against 88 for the before-version’sCharacter(printed by a scratch program with GCC and Clang on x86-64 Linux; other platforms may differ), and it holds no mask at all.- The client computes the extrinsic state.
add_lineplaces each character after the previous one using the shared glyph’s width, and sets the colour from the style. highlightchanges onePlacedGlyph, never aGlyph(FR-2). The glyph isconstthrough the pointer, so the compiler rejects an attempt to change it.
class Glyph final
the flyweight: immutable, not copyable
Data members
GlyphKey key_;character, font, size: intrinsicint width_;intrinsicstd::vector<std::uint8_t> mask_;intrinsic: size x size bytes
Member functions
explicit Glyph(GlyphKey key);rasterises; throws for bad inputconst GlyphKey& key() const;int width() const;std::span<const std::uint8_t> mask() const;
class GlyphCache
the flyweight factory: owns every glyph; not copyable
Data members
std::map<GlyphKey, Glyph> glyphs_;node-based: glyphs never move
Member functions
const Glyph& get(char character, const std::string& font, int size);made on first requeststd::size_t size() const;std::size_t mask_bytes() const;
class Document
the client: keeps the extrinsic state
Data members
GlyphCache* cache_;borrowed: must outlive the documentstd::vector<std::vector<PlacedGlyph>> lines_;each: glyph pointer, x, y, colourint next_y_;
Member functions
void add_line(std::string_view text, const Style& style);void highlight(std::size_t line, std::size_t column, Colour colour);throws std::out_of_rangeconst PlacedGlyph& at(std::size_t line, std::size_t column) const;throws std::out_of_rangestd::size_t characters() const;
The outline leaves out GlyphKey, PlacedGlyph, and Style, which are
plain structs shown in the code above, and the stand-in font library
functions rasterise and advance.
Ownership and lifetime
Section titled “Ownership and lifetime”- The cache owns every glyph, for as long as the cache lives. Nothing else owns a glyph, and no glyph is destroyed while the cache exists.
- Every
PlacedGlyphobserves a glyph through aconst Glyph*. It is valid only while the cache lives, so the cache must outlive every document that uses it. Inmain, the cache is declared before the document, so the document is destroyed first. A document that outlived its cache would hold dangling pointers in every character. - The pool only grows. Glyphs are never removed, so a pointer, once handed out, stays valid for the cache’s whole life. That is what makes plain observer pointers enough. It also means an editor that opens many documents in many fonts and sizes keeps every glyph it ever made.
- Removing unused glyphs changes the ownership. To free glyphs no
document uses any more, the cache would have to know who still uses
each one, for example by handing out
std::shared_ptr<const Glyph>and keepingstd::weak_ptrs itself. That costs a reference count per glyph and a larger pointer in every character, so do it only when the pool really grows without bound. - Threads: a glyph, once made, can be read from many threads.
getchanges the map, so a cache shared between threads needs a lock aroundgetand around every other function that reads the map (sizeandmask_bytes). A glyph obtained through the lockedgetcan then be read from any thread without a lock.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Objects in one scope are destroyed in reverse order of declaration, so// the cache, declared first, is destroyed last, after the document that// points into it.GlyphCache cache; // declared first: the document points into itDocument doc{cache};// The same text as before. This time the font library is called only// for the first copy of each different character in each style.for (int i = 0; i < 50; ++i) { doc.add_line(text, body);}doc.add_line("THE END", heading);// cache.size() is how many different glyphs exist, and mask_bytes adds// up each glyph's mask once, however many places use it.std::cout << "after: " << doc.characters() << " characters, " << cache.size() << " glyphs, " << cache.mask_bytes() << " mask bytes\n";
// The first 't' on line 0 and the first 't' on line 1 share a glyph,// but each has its own position and colour.doc.highlight(0, 0, Colour::red); // line 0, column 0: the first 't'const PlacedGlyph& first = doc.at(0, 0);const PlacedGlyph& second = doc.at(1, 0);// Comparing the two pointers asks "is it the same object in memory?",// not "do the glyphs look alike?". `?:` picks "yes" or "no" to print.std::cout << "same glyph: " << (first.glyph == second.glyph ? "yes" : "no") << "\n";std::cout << "line 0: y " << first.y << ", " << (first.colour == Colour::red ? "red" : "black") << "\n";std::cout << "line 1: y " << second.y << ", " << (second.colour == Colour::red ? "red" : "black") << "\n";// Column 4 of "the cat..." is the 'c'. Inside the string, \" prints a// double quote instead of ending the string.std::cout << "'c' in \"cat\" starts at x " << doc.at(0, 4).x << "\n";before: 1107 characters, 1107 masks, 285632 mask bytesafter: 1107 characters, 16 glyphs, 6016 mask bytessame glyph: yesline 0: y 0, redline 1: y 20, black'c' in "cat" starts at x 28Read the output against the requirements:
- 1107 characters, 16 glyphs. “the cat sat on the mat” has 10
different characters (counting the space) in
Mono16; “THE END” has 6 inMono24. Those 16 glyphs are all the font library was asked for (C-1), against 1107 calls before. - 6016 mask bytes, against 285632 (FR-3): 10 masks of 16 x 16 bytes and 6 of 24 x 24, instead of one per character. This counts only the masks; see Is it worth it? for what it does not count.
same glyph: yes, but line 0’stis red and line 1’s is black, at different heights (FR-2). Highlighting changed one place only.'c'starts at x 28: the widths oft,h, ande(8 each) and the space (4), computed by the document from the shared glyphs (FR-1).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// static_assert is checked by the compiler, not when the tests run: if a// Glyph or a GlyphCache could be copied, this file would not compile.// std::is_copy_constructible_v<T> is true when a T can be made by copying// another T; the `!` in front demands that it is false.static_assert(!std::is_copy_constructible_v<Glyph> && !std::is_copy_assignable_v<Glyph>);static_assert(!std::is_copy_constructible_v<GlyphCache>);
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if// the condition is false; LLD_CHECK_EQ(actual, expected) does the same when// the two differ, and prints both; LLD_CHECK_THROWS(expression, type) fails// unless the expression throws that type of exception. They come from the// site's small test header, lld_test.hpp. `body` is Mono at size 16.
// Five 'a's over two lines, all Mono 16: one glyph is made, both lines point// at that same object, and only one 16 x 16 mask exists.LLD_TEST(the_same_character_font_and_size_share_one_glyph) { GlyphCache cache; Document doc{cache}; doc.add_line("aaaa", body); doc.add_line("a", body); LLD_CHECK_EQ(cache.size(), std::size_t{1}); // Equal pointers mean the very same glyph, not just a similar one. LLD_CHECK(doc.at(0, 0).glyph == doc.at(1, 0).glyph); LLD_CHECK_EQ(cache.mask_bytes(), std::size_t{16 * 16});}
// The key is all three values: changing only the size, or only the font,// gives a separate glyph. &small is the address of the glyph `small` refers// to, so the check compares objects, not their contents.LLD_TEST(a_different_font_or_size_is_a_different_glyph) { GlyphCache cache; const Glyph& small = cache.get('a', "Mono", 16); const Glyph& large = cache.get('a', "Mono", 24); const Glyph& serif = cache.get('a', "Serif", 16); LLD_CHECK(&small != &large && &small != &serif); LLD_CHECK_EQ(cache.size(), std::size_t{3});}
// Two 't's share one glyph, yet highlighting the second leaves the first// black, and each has its own x: the second starts after the first's width,// 16 / 2 = 8 pixels.LLD_TEST(position_and_colour_belong_to_each_place) { GlyphCache cache; Document doc{cache}; doc.add_line("tt", body); doc.highlight(0, 1, Colour::red); LLD_CHECK(doc.at(0, 0).glyph == doc.at(0, 1).glyph); LLD_CHECK(doc.at(0, 0).colour == Colour::black); LLD_CHECK(doc.at(0, 1).colour == Colour::red); LLD_CHECK_EQ(doc.at(0, 0).x, 0); LLD_CHECK_EQ(doc.at(0, 1).x, 8);}
// Take a reference to one glyph, then add 128 more ('b' at every size from// 1 to 128). If the cache moved glyphs as it grew, `first` would now dangle.// The check proves that asking again gives the same address, and that the// old reference still reads the right glyph.LLD_TEST(glyphs_stay_where_they_are_as_the_cache_grows) { GlyphCache cache; const Glyph& first = cache.get('a', "Mono", 16); for (int size = 1; size <= 128; ++size) { cache.get('b', "Mono", size); } LLD_CHECK(&cache.get('a', "Mono", 16) == &first); LLD_CHECK_EQ(first.key().character, 'a');}
// An empty font and a size of 0 are both refused by rasterise, and a failed// request leaves nothing behind in the cache: its size is still 0.LLD_TEST(a_glyph_that_cannot_be_made_is_not_cached) { GlyphCache cache; LLD_CHECK_THROWS(cache.get('a', "", 16), std::invalid_argument); LLD_CHECK_THROWS(cache.get('a', "Mono", 0), std::invalid_argument); LLD_CHECK_EQ(cache.size(), std::size_t{0});}
// One line of two characters: column 2 does not exist, and neither does// line 1. Both throw std::out_of_range, from the vectors' .at().LLD_TEST(a_place_outside_the_document_is_refused) { GlyphCache cache; Document doc{cache}; doc.add_line("ab", body); LLD_CHECK_THROWS(doc.at(0, 2), std::out_of_range); LLD_CHECK_THROWS(doc.highlight(1, 0, Colour::red), std::out_of_range);}the_same_character_font_and_size_share_one_glyphchecks the sharing by comparing addresses.position_and_colour_belong_to_each_placechecks that highlighting one of twots leaves the other alone.glyphs_stay_where_they_are_as_the_cache_growsadds 128 glyphs after taking a reference, then checks that the reference still names the same glyph: the property that makes the observer pointers safe.
Limits of the example
Section titled “Limits of the example”rasteriseis a stand-in: its masks have the right size, and are not real shapes. Real font libraries often cache glyphs themselves, in which case the application may not need its own cache.charcovers only single-byte characters. Real text is Unicode, and what is drawn is often decided per cluster of code points, not per byte; the key would change, and the pattern would not.
Is it worth it?
Section titled “Is it worth it?”The example counts mask bytes. It does not measure the whole program’s memory or speed, and the page does not claim either. Before you use the pattern, look at what it costs, not just what it saves:
- It saves one copy of the intrinsic state for every repeat. Here, that is a 256- or 576-byte mask, a font name, and a size, per character.
- It costs one map node per distinct glyph, a lookup (and a key holding a copy of the font name) per character when laying out, a pointer per character, and the lifetime rules above.
The saving is large when the intrinsic state is large and often repeated, as here. It is small or negative when:
- The objects are few. A dialog box with forty characters does not need a cache.
- The shared part is small. If the intrinsic state is one
int, a pointer to it is at least as large as theint(typically 8 bytes against 4). - There are few repeats. If almost every object is different, the cache holds as many objects as before, plus the map’s overhead.
When the saving is not obvious from the sizes, measure the real program with a memory profiler, on realistic data, before and after. An estimate like “1107 masks against 16” is a reason to measure, not a result.
When to use it
Section titled “When to use it”- A program holds very many objects (thousands to millions): characters in a document, tiles in a game map, trees in a forest, particles, cells in a spreadsheet.
- Much of each object’s state repeats, and that part is large or expensive to make.
- The repeated part can be made immutable, and the rest can be kept by the client or passed in.
- Object identity does not matter: no code needs two
tglyphs to be different objects.
When not to use it
Section titled “When not to use it”- The objects are few, or the shared part is small. See above.
- The “shared” state must change per use. If some code needs to change a glyph for one place only, the state is not really intrinsic; move it out, or do not share.
- The repeated values are small. Short strings already fit inside
the
std::stringobject itself (the small-string optimisation; how short depends on the library), so sharing them saves little. For repeated small values, anenumor a small integer id into a table is often enough. - The library already does it. Font libraries, image caches, and string interning in some libraries share objects for you.
- The split must be right, and stay right. A requirement that makes intrinsic state vary per use (such as “let users kern one pair of letters”) means moving data out of the flyweight and into every client.
- Extrinsic state moves to the client, which must store it or compute it and pass it in. The client’s code grows.
- Lifetimes are tied to the pool. Every use is an observer of an object owned elsewhere.
- A lookup per use. Laying out a character now searches a map. For most programs that is cheap next to drawing; in a tight loop, measure.
Common misuse
Section titled “Common misuse”- Mutable flyweights. A
Glyphwith aset_colourwould colour every use at once. If a shared object has setters, it is not safe to share. - Extrinsic state in the key. Putting the colour into
GlyphKey“fixes” highlighting, but makes a new glyph, with its own mask, for every colour, and the colour still belongs to each place, not to the shape. - A
std::vectoras the pool. References to its elements dangle when it grows. Use a node-based container, or storestd::unique_ptrs in the vector so that the objects themselves do not move. - Using it without counting. A flyweight added “for performance” without a count or a measurement adds lifetime rules and gains nothing that anyone has seen.
When the requirements change
Section titled “When the requirements change”- “Support bold and italic.” Part of the shape, so part of the key:
GlyphKey,Style, and the parameters ofGlyphCache::getgain a weight and a slant.PlacedGlyphand the sharing do not change. - “Underline one word.” Per place, so extrinsic:
PlacedGlyphgains a flag. The glyphs do not change. - “Close a document and free its glyphs.” The pool must learn who
uses each glyph: see the
std::shared_ptrandstd::weak_ptrnote above. - “Lay out on several threads.” A lock around
GlyphCache::get, or one cache per thread at the cost of some duplicate glyphs.
Exercise
Section titled “Exercise”Exercise: Identify intrinsic and extrinsic state
A map app draws forests: up to 200,000 trees on screen. For each tree it knows:
- the species (oak, pine, birch: 12 species in all);
- a 3D model and a texture for the species, about 2 MB per species;
- the tree’s position on the map;
- its height, as a scale applied to the model;
- its health (healthy, dry, or dead), which changes the colour it is drawn with;
- a name, for the few trees that are landmarks.
- Sort each item into intrinsic and extrinsic state. Explain any that could go either way.
- Sketch the C++ types: the flyweight, its key, the factory, and what each tree stores.
- Estimate the saving, roughly, and say what you would measure before believing it.
- A designer asks for “a few special oaks with a different bark”. What changes?
Show the explained answer
1.
- Intrinsic (the same for every tree of a species): the species itself, the model, and the texture.
- Extrinsic (per tree): the position, the height scale, and the health.
- Health could go either way. If “dry” and “dead” only change a colour applied when drawing, health is extrinsic: a small value per tree. If each state has its own texture, the texture for (species, health) is intrinsic, and health becomes part of the key: 36 flyweights instead of 12. Either is sound; what matters is that health is not stored in a shared object and then changed.
- The landmark name is extrinsic, and rare. Storing a
std::stringin all 200,000 trees for a few names wastes space; keep names in a separatestd::mapfrom a stable tree id (add one toTree, or use its index if trees are never removed or reordered) to name.
2.
enum class Species { oak, pine, birch /* ... 12 in all */ };enum class Health { healthy, dry, dead };
// The intrinsic state: one model and texture per species, about 2 MB each,// shared by every tree of that species.class TreeModel final { // the flyweight: immutable, not copyablepublic: explicit TreeModel(Species species); // loads the model and texture // No copies: a copy would load or hold a second 2 MB for the same species. TreeModel(const TreeModel&) = delete; TreeModel& operator=(const TreeModel&) = delete; // ... const accessors onlyprivate: Species species_; std::vector<std::byte> model_; // the 3D model for the species std::vector<std::byte> texture_; // its texture};
// Makes each TreeModel once, on first request, and owns all of them, like// GlyphCache above. Here the key is just the species.class TreeModels { // the factorypublic: const TreeModel& get(Species species); // loads on first requestprivate: // As with the glyphs, std::map keeps each model in its own node, so the // references get hands out stay valid as more species are loaded. std::map<Species, TreeModel> models_; // node-based: never moves};
// One of these for each of the 200,000 trees: only what differs from tree// to tree, plus a pointer to the shared model. Health is here, not in// TreeModel, because it changes per tree.struct Tree { // per tree: the extrinsic state const TreeModel* model; // observer: TreeModels must outlive the forest float x; // the position on the map float y; float scale; // its height, as a scale applied to the model Health health;};3. Without sharing, each tree would carry about 2 MB, so 200,000
trees would need about 400 GB, which is not possible. With sharing,
the 12 models take about 24 MB, and each Tree is a pointer, three floats, and a small enum: about 24 bytes on a typical
64-bit platform, so 200,000 trees take about 5 MB. That is the kind of
difference where the pattern is clearly worth it. Still measure the
real program’s memory with realistic forests, and the time to draw
them, because the drawing code and the graphics library may have costs
this estimate ignores.
4. “A different bark” is a different texture, which is intrinsic.
Make a new flyweight for it: add a variant to the key, such as
(Species::oak, Bark::special), and point the special oaks at it. Do
not give the shared oak a setter, or every oak on the map would
change.
Related patterns
Section titled “Related patterns”- Proxy can stand in for a flyweight that is expensive to make, and create it only when first drawn. See Proxy.
- Composite trees often have many identical leaves, such as the characters of a document; those leaves can be flyweights, as long as they do not store a parent pointer, which is extrinsic. See Composite.
- Object Pool also keeps objects for reuse, but hands each one to one user at a time and takes it back; a flyweight is shared by many users at once.
- Performance: allocation, locality, and data layout looks at memory layout more broadly.
Summary
Section titled “Summary”- Flyweight saves memory when very many objects repeat a large part of their state: share that part (intrinsic state) in one immutable object, and keep the rest (extrinsic state) with each use.
- A factory makes each flyweight once per key and hands out references; it owns them, and its container must never move them.
- Every user observes a flyweight, so the factory must outlive every user.
- The hardest step is the split: anything that can differ from one use to the next is extrinsic, even when it looks like part of the object.
- Count, and then measure, before relying on the savings. With few objects, small shared parts, or few repeats, the pattern costs more than it saves.