Skip to content

Proxy

Difficulty: Intermediate

Key concepts

  • proxy pattern
  • virtual proxy
  • protection proxy
  • lazy loading
  • lifetime of the real subject
  • What the Proxy pattern is for: a stand-in that has the same interface as a real object and controls access to it, for example by creating it only when it is needed, or by checking who may use it.
  • How to write a lazy (virtual) proxy in C++, and why its const functions need a mutable member.
  • Who owns the real object, when it is created, when it is destroyed, and what happens to references into it.
  • How a proxy differs from a decorator, which has the same shape.
  • When loading everything up front, or a plain cache, is simpler.

A photo app shows a gallery: a list of the user’s photos, with each photo’s name and size, from which the user opens one to view it.

  1. FR-1 The list appears straight away. The names and sizes come from a catalogue file that is read when the gallery opens.
  2. FR-2 A photo’s pixels are loaded from disk only when the user opens it, and only once while it stays open.
  3. FR-3 A photo that cannot be loaded (deleted, or damaged) gives an error for that photo only; the rest of the gallery still works.
  4. FR-4 When memory runs low, the app can free the pixels of photos that are not on screen, and load them again later.
  5. C-1 (constraint) Code that shows or processes images works with an Image interface and must not change.

Loading a photo is slow and takes memory; galleries hold thousands of photos, and the user opens a few.

The interface the app already has, the real image class, and the store images are loaded from:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

image.hpp
// The subject: what the gallery needs from any image. It is an interface:
// every function is pure virtual (`= 0`), so Image says what an image can
// answer and leaves how to each class that derives from it. Client code
// holds an Image by reference or through a std::unique_ptr<Image>, and
// never knows which kind of image is behind it.
class Image {
public:
Image() = default;
// Copying is switched off (= delete). Copying through a base class
// would copy only the Image part of a Bitmap or LazyImage ("slicing"),
// and an image may hold a lot of pixels. Declaring these also means no
// move is generated, so images stay where they are made and are passed
// around by pointer or reference.
Image(const Image&) = delete;
Image& operator=(const Image&) = delete;
// Virtual, so that deleting a Bitmap or LazyImage through a
// std::unique_ptr<Image> runs the right destructor.
virtual ~Image() = default;
// The name is returned by const reference: no copy, and it stays valid
// as long as the image object itself.
virtual const std::string& name() const = 0;
virtual Size size() const = 0;
// std::span is a view: a pointer and a length into bytes that someone
// else owns. It does not copy the pixels, and it is only valid while
// the image keeps them.
virtual std::span<const std::uint8_t> pixels() const = 0; // one grey byte per pixel
};
// The real subject: an image with its pixels in memory. `final` means no
// class can derive from Bitmap. The pixels are stored row by row, one byte
// each, so a width x height image holds exactly width * height bytes.
class Bitmap final : public Image {
public:
// The arguments are taken by value and moved into the members, so a
// caller that passes a temporary vector pays no copy. Throws
// std::invalid_argument unless width and height are both positive and
// the vector holds exactly width * height pixels.
Bitmap(std::string name, Size size, std::vector<std::uint8_t> pixels); // throws if they disagree
const std::string& name() const override { return name_; }
Size size() const override { return size_; }
std::span<const std::uint8_t> pixels() const override { return pixels_; }
private:
std::string name_;
Size size_;
std::vector<std::uint8_t> pixels_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

image.hpp
// Where images are loaded from: the disk in the app, a fake in tests.
// Loading is the slow, memory-hungry step the proxy exists to put off.
class ImageStore {
public:
virtual ~ImageStore() = default;
// Makes a new image and hands it over: the std::unique_ptr<Image> means
// the caller owns the result from now on, and it is freed when that
// pointer is destroyed or reset. Throws if the image is missing or
// damaged; never returns null.
virtual std::unique_ptr<Image> load(const std::string& name) = 0;
};
// One line of the catalogue, which is read when the gallery opens. It is
// cheap: just a name and a size, with no pixels. This is all the list
// view needs.
struct CatalogueEntry {
std::string name;
Size size;
};

The gallery loads every image in the catalogue when it opens:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// Opens the gallery the eager way: asks the store to load every image in
// the catalogue, in order, and returns them all, owned by the vector. The
// catalogue is only read (const reference); the store is borrowed for the
// length of the call. Whatever load() throws passes straight out.
std::vector<std::unique_ptr<Image>> open_gallery(const std::vector<CatalogueEntry>& catalogue,
ImageStore& store) {
std::vector<std::unique_ptr<Image>> images;
for (const CatalogueEntry& entry : catalogue) {
// load() returns a temporary std::unique_ptr, so push_back moves it
// into the vector with no std::move needed. This is the slow step,
// done once per entry before anything can be shown.
// If it throws, the loop stops, `images` is destroyed on the way
// out (freeing the images already loaded), and the caller gets the
// exception instead of a gallery.
images.push_back(store.load(entry.name));
}
return images; // the vector is moved out to the caller, not copied
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// make_disk() (above) puts beach.png, forest.png, and city.png on a
// fake disk. The catalogue also lists lost.png, which is not there.
MemoryStore disk = make_disk();
try {
// Loads beach, forest, and city, then throws on lost.png. The
// vector is never finished, so `images` is never used.
const auto images = before::open_gallery(catalogue, disk);
} catch (const std::runtime_error& error) {
// error.what() is the message the store threw. disk.loads() is
// 4: three loads that worked, and the one that failed.
std::cout << "before: " << error.what() << " after " << disk.loads() << " loads\n";
}

For ten small images, this is the right design: simple, and every image is ready when it is wanted. For this app it fails three requirements:

  • FR-1: the list waits for every image to load, although it needs only names and sizes. Thousands of photos mean a long wait and a lot of memory, for pixels the user may never look at.
  • FR-3: one missing file stops the whole gallery. The output shows the gallery failing on its fourth load, with nothing shown. (Catching the error for each entry inside open_gallery would fix this one on its own; FR-1 is the requirement that loading up front cannot meet.)
  • FR-4: there is no way to free one image and get it back.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_proxy.cpp
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records
// a failure, and prints both values, if they are not equal.
// 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.
// `catalogue` and make_disk() are defined above this snippet: a catalogue
// of a.png (2x2), b.png (3x1), and c.png (1x1), and a fake disk that holds
// all three, with grey levels 10, 20, and 30.
// Just opening the before-version gallery costs one load per image: 3.
LLD_TEST(before_every_image_is_loaded_to_show_the_list) {
MemoryStore disk = make_disk();
const auto images = before::open_gallery(catalogue, disk);
LLD_CHECK_EQ(disk.loads(), 3);
}
// A catalogue with one entry the disk does not have: the whole
// open_gallery call throws, so no gallery is returned at all.
LLD_TEST(before_one_missing_file_stops_the_whole_gallery) {
MemoryStore disk = make_disk();
std::vector<CatalogueEntry> with_missing = catalogue; // a copy we can add to
with_missing.push_back({"lost.png", {1, 1}});
LLD_CHECK_THROWS(before::open_gallery(with_missing, disk), std::runtime_error);
}

MemoryStore stands in for the disk; its loads() counts every load it was asked for, including those that failed:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

memory_store.hpp
// A stand-in for the disk: makes images filled with one grey level,
// and counts every load it is asked for, including those that fail.
// Tests read loads() to prove how many times the disk was used.
class MemoryStore final : public ImageStore {
public:
// Puts an image "on the disk". Adding a name that is already there
// replaces the old entry.
void add(const std::string& name, Size size, std::uint8_t grey);
// `override` asks the compiler to check that this really replaces
// ImageStore::load. It adds one to loads() first, then throws
// std::runtime_error if no image has that name; otherwise it returns a
// new Bitmap of the stored size with every pixel set to the grey level.
// Each call makes fresh pixels: nothing is cached here.
std::unique_ptr<Image> load(const std::string& name) override;
int loads() const { return loads_; }
private:
// What is kept for each name: only the recipe (size and grey level),
// not the pixels themselves.
struct Stored {
Size size;
std::uint8_t grey;
};
std::map<std::string, Stored> images_; // name -> recipe, looked up by name
int loads_ = 0; // every load() call, failed or not
};

The usual first fix is to make the client check: keep a loaded flag next to each entry, and load before every use. That works, but every piece of code that touches pixels must remember the check, and C-1 says that code must not change.

Data or job Needs the pixels? Where it can be answered
the image’s name no the catalogue
the image’s width and height no the catalogue
the pixels yes only the real image, after a load
whether the image is loaded no whatever holds the real image
loading, and loading only once - whatever holds the real image
freeing the pixels - whatever holds the real image
average grey, drawing, and so on yes client code, through the Image interface (C-1)

Two rows can be answered without the real image, and three are about managing the real image. Something must hold the catalogue entry, decide when to load, and own what was loaded, while still looking like an Image to the client. That is a proxy.

Proxy puts a stand-in object in front of a real one. The stand-in has the same interface, so the client cannot tell them apart, and it decides how and when the call reaches the real object.

Its participants:

  • The subject: the interface the client uses. Here, Image.
  • The real subject: the object that does the real work. Here, Bitmap.
  • The proxy: implements the subject, holds or reaches the real subject, and controls access to it. Here, LazyImage.

Proxies are often named by what they control:

  • A virtual proxy creates an expensive real subject only when it is first needed. LazyImage is one.
  • A protection proxy checks whether the caller may use the real subject. The exercise builds one.
  • A caching proxy keeps results so that the real subject is not asked twice for the same thing.
  • A remote proxy stands for an object in another process or on another machine, and turns calls into messages.
LazyImage and Bitmap both implement Image; LazyImage owns the real image once it is loaded, and borrows the store it loads from
Text description of the diagram

A class diagram. Image is an interface with three pure virtual functions: name, which returns a constant string reference; size; and pixels, which returns a span of constant bytes. Bitmap implements Image and holds a name, a size, and a vector of bytes. LazyImage also implements Image; it holds a catalogue entry, a pointer to an ImageStore, and a unique pointer to an Image called real_, and it adds loaded and unload functions. ImageStore is an interface with a load function that takes a name and returns a unique pointer to an Image. A filled-diamond composition line shows that a LazyImage owns zero or one Image through real_, once it has loaded it. A plain arrow shows that a LazyImage borrows an ImageStore through store_.

Diagram source (Mermaid)
classDiagram
class Image {
  <<interface>>
  +name() const string&*
  +size() Size*
  +pixels() span~const uint8_t~*
}
class Bitmap {
  -string name_
  -Size size_
  -vector~uint8_t~ pixels_
}
class LazyImage {
  -CatalogueEntry entry_
  -ImageStore* store_
  -unique_ptr~Image~ real_
  +loaded() bool
  +unload() void
}
class ImageStore {
  <<interface>>
  +load(name) unique_ptr~Image~*
}
Image <|.. Bitmap
Image <|.. LazyImage
LazyImage *-- "0..1" Image : real_ (owns, once loaded)
LazyImage --> ImageStore : store_ (borrows)

LazyImage owns an Image, not a Bitmap: it depends only on the interface, and does not care what the store makes.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

lazy_image.hpp
// A proxy that stands in for an image and loads it only when its pixels
// are first needed. The name and size come from the catalogue.
// It derives from Image, the same interface as the real Bitmap, so any
// code written for Image accepts a LazyImage without knowing it is one.
// Making one is cheap and cannot fail on a missing file: nothing is read
// until pixels() is called.
class LazyImage final : public Image {
public:
// Keeps its own copy of the catalogue entry (taken by value, then moved
// in), and remembers which store to load from. Loads nothing.
LazyImage(CatalogueEntry entry, ImageStore& store);
// These two answer from the copied catalogue entry, so they never
// touch the store, even for a file that is missing.
const std::string& name() const override { return entry_.name; }
Size size() const override { return entry_.size; } // never loads
// Loads the real image the first time, then reuses it. Throws if the
// load fails or the file's size disagrees with the catalogue; after a
// throw the proxy is still unloaded, and the next call tries again.
std::span<const std::uint8_t> pixels() const override; // loads on first use
// Not part of Image: only code that knows it holds a LazyImage (a
// memory manager, or a test) can ask this or call unload().
bool loaded() const { return real_ != nullptr; }
// Frees the pixels; they are loaded again if needed. Any span from
// pixels() dangles after this.
// reset() destroys the image real_ owns and leaves real_ null. It is
// not const: it needs a LazyImage the caller may change.
void unload() { real_.reset(); }
private:
// The loaded image, loading it first if real_ is still null.
const Image& real() const;
CatalogueEntry entry_; // the proxy's own copy: name and expected size
// A plain pointer here means "borrowed": the proxy uses the store but
// never deletes it.
ImageStore* store_; // borrowed: must outlive the proxy
// The real subject, once loaded. std::unique_ptr: the proxy is its only
// owner and frees it when the proxy is destroyed or unloads. `mutable`
// lets the const pixels() fill it in; the page explains why that is
// allowed here.
mutable std::unique_ptr<Image> real_; // owned; null until first needed
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

lazy_image.cpp
// The only function that needs the real image: make sure it is loaded,
// then pass the request on to it. The span returned points into the
// pixels owned by real_, so it is valid until unload() or the proxy's end.
std::span<const std::uint8_t> LazyImage::pixels() const { return real().pixels(); }
// Returns the real image, loading it on the first call. Throws
// std::runtime_error if the store returns null or an image whose size is
// not the catalogue's; anything the store's load() throws passes through.
// If it throws, real_ is left exactly as it was: still null.
const Image& LazyImage::real() const {
// A std::unique_ptr converts to false when it is null, so this reads
// "if nothing is loaded yet". When an image is loaded, skip to return.
if (!real_) {
// Load into a local first, not straight into real_. If the load or
// either check below throws, real_ has not been touched, and the
// local `image` frees whatever was loaded as the exception leaves.
// store_ is a pointer, so -> calls through it.
std::unique_ptr<Image> image = store_->load(entry_.name); // may throw: stay unloaded
// ImageStore promises never to return null, but the proxy checks
// anyway, so a broken store gives an error, not a crash below.
if (!image) {
throw std::runtime_error{"the store returned no image for " + entry_.name};
}
// The list already showed entry_.size, so a file of another size
// is refused. `!=` compares width and height (Size has a defaulted
// ==, and C++20 builds != from it).
if (image->size() != entry_.size) {
throw std::runtime_error{entry_.name + " is not the size the catalogue says"};
}
// Everything passed: hand ownership from the local to the member.
// std::move is needed because a unique_ptr cannot be copied; after
// this, `image` is null and real_ owns the loaded image.
real_ = std::move(image);
}
// *real_ is the Image that real_ points to; return a reference to it.
return *real_;
}
How this code works: LazyImage::real

pixels() is one line: it calls real() and asks the result for its pixels. All the work is in real(), which has two paths.

  1. Already loaded. real_ is not null, so if (!real_) is false, the whole block is skipped, and return *real_ hands back the image loaded earlier. The store is not asked again.
  2. Not loaded yet. real_ is null, so the block runs:
    1. store_->load(entry_.name) asks the store for the image and puts the result in a local std::unique_ptr called image. If the store throws (for example, the file is missing), the function stops here and real_ is still null.
    2. If the store returned null, throw. image is null, so nothing needs freeing.
    3. If the loaded image’s size is not the catalogue’s, throw. As the exception leaves the function, the local image is destroyed, and the image it owned is freed with it. real_ is still null.
    4. Only now, with every check passed, real_ = std::move(image) moves ownership into the member. From here on, the proxy is loaded.
    5. return *real_ hands back a reference to the new image.

The order inside step 2 is the whole trick: nothing the client can see changes until the last line that could throw has passed. That is what makes a failed load safe to retry.

Here is the test a_failed_load_leaves_the_proxy_unloaded_and_is_tried_again traced through real(). The proxy is for late.png, 1 × 1, and the disk starts empty.

Step Path in real() real_ afterwards disk.loads()
make the proxy not called null 0
image.pixels() not loaded: load throws null 1
disk.add("late.png", {1, 1}, 99) not called null 1
average_grey(image) not loaded: load and checks pass owns a 1 × 1 image 2
another average_grey(image) (if it were called) already loaded unchanged 2

average_grey returns 99, because the one pixel is 99. The last row is not in that test; the test the_pixels_are_loaded_once checks it.

  • name() and size() answer from the catalogue and never load (FR-1). Only pixels() goes through real().
  • real() loads once (FR-2). The first call loads and keeps the image; later calls find real_ set and return it.
  • A failed load leaves the proxy unloaded (FR-3). real_ is set only after the load and the checks have all succeeded, so if any of them throws, the proxy is as it was, and the next call tries again. This is the strong exception guarantee for the proxy; the store’s own side effects, such as its load count, are not undone.
  • The proxy keeps its word. The list showed the catalogue’s size. If the file turns out to have a different size, the proxy refuses it rather than quietly giving the client an image that contradicts what it was told before.
  • unload() frees the pixels (FR-4) by resetting real_. It is on LazyImage, not on Image, because only a proxy has anything to free; the code that manages memory holds LazyImages.

pixels() is const in Image, and it should be: reading the pixels does not change the image, as far as the client can tell. But the proxy’s pixels() must store what it loads. mutable allows a const function to change that one member.

That is a promise: the change is invisible to the client. Everything the Image interface answers is the same before and after the load (only loaded(), which is not part of Image, changes). Keep mutable for exactly this kind of member (caches, lazily loaded parts, and locks), and never for state the client could notice.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

gallery.hpp
// The client: works with any Image, real or proxy.
// These functions use only the Image interface, so they are the same code
// whether the vector holds Bitmaps or LazyImages.
// One line per image, "name WIDTHxHEIGHT", for example "beach.png 4x3".
// It reads only name() and size(), so it never makes a proxy load.
std::string listing(const std::vector<std::unique_ptr<Image>>& images); // names and sizes
// The mean of the image's pixel bytes, rounded down. It reads pixels(),
// so a proxy loads here, and a failed load throws out of this function.
int average_grey(const Image& image); // needs the pixels
// Makes one LazyImage per catalogue entry, in order. Every proxy borrows
// `store`, so the store must outlive the returned images.
std::vector<std::unique_ptr<Image>> open_gallery(const std::vector<CatalogueEntry>& catalogue,
ImageStore& store); // loads nothing

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

gallery.cpp
// The same signature as the before-version, so its callers do not change.
// The only difference is the line inside the loop: it makes a proxy
// instead of loading. Making a proxy touches no file, so this cannot fail
// because an image is missing.
std::vector<std::unique_ptr<Image>> open_gallery(const std::vector<CatalogueEntry>& catalogue,
ImageStore& store) {
std::vector<std::unique_ptr<Image>> images;
for (const CatalogueEntry& entry : catalogue) {
// std::make_unique<LazyImage>(entry, store) creates a LazyImage on
// the heap, copying the entry into it and passing the store by
// reference. The std::unique_ptr<LazyImage> it returns converts to
// a std::unique_ptr<Image> as it goes into the vector: a LazyImage
// is an Image, and the vector now owns it.
images.push_back(std::make_unique<LazyImage>(entry, store));
}
return images;
}

listing and average_grey take Images, and work the same on a Bitmap or a LazyImage (C-1). Only open_gallery changed: it makes proxies instead of loading. It returns a std::vector of std::unique_ptr<Image> like the before-version, so its callers do not change either. Destroying them through std::unique_ptr<Image> is correct for both kinds because Image’s destructor is virtual.

The first call to pixels loads the image through the store; the second goes straight to the loaded image
Text description of the diagram

A sequence diagram with four participants: the client functions listing and average_grey, a LazyImage proxy, the ImageStore, and the Bitmap. The client (listing) asks the proxy for the name and size, and the proxy answers from the catalogue without contacting anything else. The client (average_grey) then asks the proxy for its pixels. The proxy asks the store to load the image by name and receives a unique pointer to it. The proxy checks the loaded image’s size against the catalogue, then asks the Bitmap for its pixels and passes the span back to the client. When the client asks for the pixels again, the proxy goes straight to the Bitmap, with no load.

Diagram source (Mermaid)
sequenceDiagram
participant Client as listing() and average_grey()
participant Proxy as LazyImage
participant Store as ImageStore
participant Real as Bitmap
Client->>Proxy: name(), size()
Proxy-->>Client: from the catalogue
Client->>Proxy: pixels()
Proxy->>Store: load(name)
Store-->>Proxy: unique_ptr to Image
Proxy->>Real: size()
Real-->>Proxy: matches the catalogue
Proxy->>Real: pixels()
Real-->>Proxy: span
Proxy-->>Client: span
Client->>Proxy: pixels(), again
Proxy->>Real: pixels()
Real-->>Proxy: span
Proxy-->>Client: span

interface (abstract class) Image

the subject: not copyable

Member functions

  • virtual const std::string& name() const = 0;
  • virtual Size size() const = 0;
  • virtual std::span<const std::uint8_t> pixels() const = 0;

class Bitmap final

the real subject: pixels in memory

Data members

  • std::string name_;
  • Size size_;
  • std::vector<std::uint8_t> pixels_; width times height

Member functions

  • Bitmap(std::string name, Size size, std::vector<std::uint8_t> pixels); throws std::invalid_argument for a bad size or the wrong number of pixels

class LazyImage final

the proxy: loads on first use

Data members

  • CatalogueEntry entry_; name and size, from the catalogue
  • ImageStore* store_; borrowed: must outlive the proxy
  • mutable std::unique_ptr<Image> real_; owned; null until loaded

Member functions

  • LazyImage(CatalogueEntry entry, ImageStore& store);
  • bool loaded() const;
  • void unload(); spans from pixels() dangle after this

interface (abstract class) ImageStore

where images come from

Member functions

  • virtual std::unique_ptr<Image> load(const std::string& name) = 0; throws if missing
The gallery's images: the Image interface, the real Bitmap, the LazyImage proxy, and the store it loads from

The outline leaves out the overrides of name, size, and pixels, and MemoryStore, the example’s stand-in for the disk.

  • The proxy owns the real subject, once it exists. The store hands over a std::unique_ptr<Image>; the proxy keeps it in real_; the real image is destroyed when the proxy is destroyed or unloads.
  • The real subject’s lifetime is shorter than the proxy’s, and can start and end several times. That is the point of FR-4, and it has a cost:
  • Spans into the pixels dangle after unload(). pixels() returns a std::span, which points into the Bitmap’s vector without owning it. After unload(), that vector is gone. Code that keeps a span must not call unload() (or destroy the proxy) while it uses it. The comment on unload() says so. A design that needed long-lived views could hand out std::shared_ptr<const Image> instead, at the cost of shared ownership, but that is a new function or a change to the Image interface, which C-1 rules out here.
  • The store is borrowed. Every proxy holds a pointer to the ImageStore, which must outlive all of them. In main, the store is declared before the gallery, so the gallery is destroyed first.
  • The catalogue entry is copied into each proxy, so the catalogue can be thrown away after the gallery opens.

Other kinds of proxy own differently. A protection proxy usually owns the object it guards, as in the exercise. A proxy for an object that other code also uses, such as a shared connection, borrows it and must not outlive it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The disk is declared before the gallery, so it is destroyed after
// it: every proxy borrows the disk and must not outlive it.
MemoryStore disk = make_disk();
// Four proxies, one per catalogue entry, in catalogue order:
// images[0] beach, [1] forest, [2] city, [3] lost. Nothing is loaded.
const auto images = open_gallery(catalogue, disk);
// The list reads only names and sizes, which the proxies answer from
// the catalogue, so the count printed next is still 0.
std::cout << listing(images);
std::cout << "loads: " << disk.loads() << "\n";
// *images[0] turns the std::unique_ptr<Image> into the Image it points
// to, which is what average_grey takes. The first call loads beach.png;
// the second finds it already loaded. The count goes from 0 to 1.
std::cout << "beach.png average grey: " << average_grey(*images[0]) << "\n";
std::cout << "beach.png average grey: " << average_grey(*images[0]) << "\n";
std::cout << "loads: " << disk.loads() << "\n";
// lost.png is in the catalogue but not on the disk, so its load throws
// (count 2). The print inside `try` is skipped, the error is reported,
// and that one proxy stays unloaded. The rest of the gallery still works.
try {
const int grey = average_grey(*images[3]);
std::cout << "lost.png average grey: " << grey << "\n";
} catch (const std::runtime_error& error) {
std::cout << "could not open lost.png: " << error.what() << "\n";
}
// city.png loads now, for the first time: the count ends at 3.
std::cout << "city.png average grey: " << average_grey(*images[2]) << "\n";
std::cout << "loads: " << disk.loads() << "\n";
Expected output
before: no image named lost.png after 4 loads
beach.png 4x3
forest.png 3x3
city.png 2x2
lost.png 5x5
loads: 0
beach.png average grey: 200
beach.png average grey: 200
loads: 1
could not open lost.png: no image named lost.png
city.png average grey: 120
loads: 3

Read the output against the requirements:

  • The before: line: the before-version tried 4 loads; the fourth, lost.png, failed, so nothing was shown.
  • The list appears with loads: 0 (FR-1), including lost.png, which does not exist: the catalogue says it does.
  • Opening beach.png twice costs one load (FR-2).
  • Opening lost.png fails for that photo only, and city.png opens after it (FR-3). The count is 3: beach.png, the failed lost.png, and city.png.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_proxy.cpp
// Checked when the test file is compiled, not when it runs: the build
// fails unless LazyImage derives from Image, so it can go anywhere an
// Image can.
static_assert(std::is_base_of_v<Image, LazyImage>);
// FR-1: the list shows every name and size, and the disk is never used.
LLD_TEST(the_list_needs_no_loads) {
MemoryStore disk = make_disk();
const auto images = open_gallery(catalogue, disk);
LLD_CHECK_EQ(listing(images), std::string{"a.png 2x2\nb.png 3x1\nc.png 1x1\n"});
LLD_CHECK_EQ(disk.loads(), 0);
}
// The same client functions, run on real Bitmaps (eager) and on proxies
// (lazy), give the same list and the same average grey for b.png.
LLD_TEST(the_client_cannot_tell_a_proxy_from_the_real_image) {
MemoryStore disk = make_disk();
const auto eager = before::open_gallery(catalogue, disk); // loads all three
const auto lazy = open_gallery(catalogue, disk); // loads nothing
LLD_CHECK_EQ(listing(lazy), listing(eager));
LLD_CHECK_EQ(average_grey(*lazy[1]), average_grey(*eager[1]));
}
// FR-2: reading the pixels twice costs one load. A LazyImage is made
// directly here, not through open_gallery, so the test can call loaded(),
// which is not part of Image. It is even const: pixels() and loaded() are
// const functions, and the load goes into the mutable real_.
LLD_TEST(the_pixels_are_loaded_once) {
MemoryStore disk = make_disk();
// {"a.png", {2, 2}} builds the CatalogueEntry in place.
const LazyImage image{{"a.png", {2, 2}}, disk};
LLD_CHECK(!image.loaded());
LLD_CHECK_EQ(average_grey(image), 10);
LLD_CHECK_EQ(average_grey(image), 10);
LLD_CHECK(image.loaded());
LLD_CHECK_EQ(disk.loads(), 1);
}
// FR-4: after unload(), the proxy is empty again, and the next use loads
// a second time. Not const this time, because unload() changes the proxy.
LLD_TEST(unload_frees_the_pixels_and_the_next_use_loads_again) {
MemoryStore disk = make_disk();
LazyImage image{{"a.png", {2, 2}}, disk};
LLD_CHECK_EQ(average_grey(image), 10);
image.unload();
LLD_CHECK(!image.loaded());
LLD_CHECK_EQ(average_grey(image), 10);
LLD_CHECK_EQ(disk.loads(), 2);
}
// FR-3: the disk starts empty, so the first load throws (load 1) and the
// proxy stays unloaded. Once the file is added, the next use loads it
// (load 2) and works: a failure is not remembered.
LLD_TEST(a_failed_load_leaves_the_proxy_unloaded_and_is_tried_again) {
MemoryStore disk; // empty: late.png is not there yet
const LazyImage image{{"late.png", {1, 1}}, disk};
LLD_CHECK_THROWS(image.pixels(), std::runtime_error);
LLD_CHECK(!image.loaded());
disk.add("late.png", {1, 1}, 99); // the file arrives
LLD_CHECK_EQ(average_grey(image), 99);
LLD_CHECK_EQ(disk.loads(), 2);
}
// The disk's a.png is 2x2, but this catalogue entry says 4x4. The load
// works, the size check throws, and the proxy keeps reporting the 4x4 the
// list already showed, rather than switching to the file's size.
LLD_TEST(an_image_that_disagrees_with_the_catalogue_is_refused) {
MemoryStore disk = make_disk();
const LazyImage image{{"a.png", {4, 4}}, disk}; // the catalogue is wrong
LLD_CHECK_THROWS(image.pixels(), std::runtime_error);
LLD_CHECK(!image.loaded());
LLD_CHECK_EQ(image.size().width, 4); // what the list showed
}
// The real subject guards itself too: a 2x2 Bitmap needs 4 pixels, and
// std::vector<std::uint8_t>(3, 0) gives it only 3 (three bytes of 0).
LLD_TEST(a_bitmap_checks_its_pixels) {
LLD_CHECK_THROWS(Bitmap("x.png", Size{2, 2}, std::vector<std::uint8_t>(3, 0)), std::invalid_argument);
}
  • the_client_cannot_tell_a_proxy_from_the_real_image runs the same client functions on the before-version’s images and on proxies, and gets the same answers.
  • a_failed_load_leaves_the_proxy_unloaded_and_is_tried_again adds the missing file after the first failure; the second try succeeds.
  • unload_frees_the_pixels_and_the_next_use_loads_again checks FR-4.
  • an_image_that_disagrees_with_the_catalogue_is_refused checks that the proxy keeps its word.
  • MemoryStore makes images in memory and is instant, so the example shows how many loads happen, not how long they take. That is the right thing to test, because it does not depend on the machine.
  • A real gallery would load in the background, so that opening a photo does not freeze the screen. Then the proxy needs a state for “loading” and a lock, and pixels() must either wait or return a placeholder.
  • Nothing decides which photos to unload. That is a cache policy, such as “least recently used”; Cache policies and invalidation compares them.

Both wrap an object behind the same interface, and the code can look the same. The real difference is the purpose. Who creates the inner object is often a clue, but not a rule: a lazy proxy creates its own, while a protection proxy, like the one in the exercise, is usually handed it, just as a decorator is.

Proxy Decorator
Purpose control access to the real object add a step to the object’s work
The inner object often created or found by the proxy itself (LazyImage loads it) usually given to the decorator by the client
Stacking often one proxy, sometimes a few (protection around lazy) often several, in an order that matters
What the client gets the same answers, at a different time or only if allowed different or extra work, such as compressed bytes

Some classes are both; the names describe intent, not a different structure. Decorator vs Proxy compares the two in detail.

  • The real object is expensive to create, and many are never used: large images, documents, database records, connections.
  • Access needs a check that should not be inside the real class or scattered through clients: permissions, rate limits, valid states.
  • The real object is somewhere else: another process, a server. The proxy hides the messages behind ordinary calls.
  • Clients must not change (C-1), so the control has to arrive through the interface they already use.
  • Everything is needed anyway, or it is cheap. Loading ten thumbnails up front is simpler than ten proxies.
  • Only one place needs the control. If one function loads lazily, a std::unique_ptr<Image> member that starts empty, and a local if, is enough.
  • Hiding the cost misleads the client. A remote proxy makes a network call look like a function call. If clients must handle timeouts and failures, give them an interface that says so, rather than a proxy that pretends to be local.
  • The interface is wide. Like a decorator, a proxy must implement every function of the subject. If most functions need the real object, the proxy is mostly forwarding code.
  • First use is slow, at a moment the client does not choose. The user waits when they open a photo, not when the gallery opens. That is usually what you want; when it is not, load ahead in the background.
  • Errors move. In the before-version, a missing file failed when the gallery opened; with proxies, it fails on pixels(), perhaps much later and far from the code that built the gallery. Every client of pixels() must be ready for an exception. Note the kinds, too: a missing file is a std::runtime_error, but a damaged file that a Bitmap refuses would be a std::invalid_argument, which main’s catch (const std::runtime_error&) does not catch.
  • mutable state in const functions makes thread safety the proxy’s job, as the warning above explains.
  • Lifetimes get more complicated: the real object can come and go, and views into it dangle when it goes.
  • A proxy that changes the answers. A proxy whose size() reports one thing before loading and another after breaks the client’s trust. This is why LazyImage refuses a mismatched image.
  • Leaking the proxy’s existence. Clients that dynamic_cast to LazyImage to call loaded() before every use have rebuilt the “check everywhere” approach. Only the memory-management code should know about proxies.
  • Proxies for cheap objects, out of habit: an extra class and an extra indirection for nothing.
  • std::shared_ptr for the real subject “to be safe”. It keeps the pixels alive as long as anyone holds them, which defeats unload(). Use it only when long-lived views are a real requirement, and then accept that unloading frees memory only when the last holder lets go.
  • “Private photos need permission.” A protection proxy around the lazy one: the exercise below.
  • “Load photos in the background.” LazyImage gains a loading state and a lock, and pixels() waits or returns a placeholder. The clients still see Image.
  • “Photos come from a cloud service.” A new ImageStore; the proxy does not change.
  • “Free the photos the user has not looked at for longest.” A cache policy that decides which proxies to unload().

Exercise: Add access checks

Some photos are private. A viewer who is not allowed must still see a private photo’s name and size in the list, but must not get its pixels.

  1. Write a ProtectedImage proxy that wraps any Image and refuses pixels() to a viewer who may not see private photos. What does it own, and what does it borrow?
  2. Build a gallery entry from a ProtectedImage and a LazyImage. Which wraps which, and what difference does the order make?
  3. The check could also go in Bitmap, in the ImageStore, or in the client code that calls pixels(). Why is a proxy a better place than each of these?
Show the explained answer

1. It owns the image it guards, and borrows the viewer:

// Who is looking at the gallery, and whether they may see private photos.
struct Viewer {
std::string name;
bool sees_private = false;
};
// Its own exception type, so callers can tell "not allowed" apart from
// "could not load". `using std::runtime_error::runtime_error;` borrows the
// base class's constructors, so AccessDenied{"message"} works.
class AccessDenied : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
// A protection proxy: the same Image interface, with a check in front of
// pixels(). Name and size pass straight through, so the list still shows a
// private photo; only its pixels are guarded.
class ProtectedImage final : public Image {
public:
// Takes ownership of `image` (std::move hands the pointer over) and
// keeps the viewer's address. Throws std::invalid_argument for a null
// image, so every function below may use image_ without checking.
ProtectedImage(std::unique_ptr<Image> image, bool is_private, const Viewer& viewer)
: image_{std::move(image)}, private_{is_private}, viewer_{&viewer} {
if (!image_) {
throw std::invalid_argument{"a protected image needs an image"};
}
}
const std::string& name() const override { return image_->name(); }
Size size() const override { return image_->size(); }
// The check runs before the wrapped image is asked for anything, so a
// refused viewer never reaches it. Allowed viewers get its pixels.
std::span<const std::uint8_t> pixels() const override {
if (private_ && !viewer_->sees_private) {
throw AccessDenied{viewer_->name + " may not see " + image_->name()};
}
return image_->pixels();
}
private:
std::unique_ptr<Image> image_; // owned: usually a LazyImage
bool private_;
const Viewer* viewer_; // borrowed: must outlive the proxy
};

AccessDenied derives from std::runtime_error, so the gallery’s existing error handling catches it, and code that cares can catch it separately.

2. The protection proxy goes outside, around the lazy one:

// Outside: the protection check. Inside: the lazy proxy, which loads only
// when an allowed viewer asks for pixels. `true` marks the photo private;
// `guest` is a Viewer, borrowed, so it must outlive `entry`.
ProtectedImage entry{std::make_unique<LazyImage>(CatalogueEntry{"diary.png", {2, 2}}, disk),
true, guest};

Then a refused viewer never causes a load: the check runs before the LazyImage is asked for anything. In a scratch program, a refused viewer caused 0 loads and an allowed viewer caused 1.

The other order, a LazyImage around a ProtectedImage, cannot be built directly, because a LazyImage is not given an Image: it gets one from its store. The only way to get that order is a store that returns ProtectedImages, so the check would run after the load. A refused viewer would still cost a slow load, and the private pixels would sit in memory. As with decorators, the order of wrappers is part of the design.

3.

  • In Bitmap: the real image would have to know about viewers and permissions, which have nothing to do with pixels, and every other kind of image would need the same code.
  • In the ImageStore: the store is asked only on the first load. After that, the LazyImage hands out its pixels without asking anyone, so a second viewer, or a viewer whose permission was taken away, is never checked.
  • In the client: every function that calls pixels() would have to remember the check, which is the problem the lazy proxy solved for loading, and C-1 says those functions must not change.

The proxy puts the check exactly where access happens, once, without changing the real image or its clients.

  • Decorator has the same structure and a different purpose: see Proxy or Decorator? above, Decorator, and Decorator vs Proxy.
  • Adapter also stands in front of an object, but gives it a different interface; a proxy keeps the same one. See Adapter.
  • Flyweight shares objects to save memory; a lazy proxy avoids creating them until they are needed. The two are often used together in image and text systems. See Flyweight.
  • Cache policies and invalidation decide what a caching proxy keeps, what it throws away, and how it learns that a result is old.
  • A proxy has the same interface as the real object, and controls how and when calls reach it: creating it late (virtual proxy), checking permission (protection proxy), keeping results (caching proxy), or reaching it elsewhere (remote proxy).
  • Clients do not change, because they cannot tell a proxy from the real object.
  • A lazy proxy in C++ owns the real object through a mutable std::unique_ptr, sets it only after a load fully succeeds, and needs a lock if threads share it.
  • The real object’s lifetime is shorter than the proxy’s: views into it dangle when it is freed.
  • Do not use a proxy when everything is needed anyway, when only one place needs the control, or when hiding the cost would mislead.