The Proxy Pattern is probably the most influential design pattern for C++. The Proxy provides a placeholder for accessing another object.
The proxy pattern is one of the seven structural patterns from the book “Design Patterns: Elements of Reusable Object-Oriented Software”. A proxy controls access to another object, allowing you to perform additional operations before or after you access the original object. Sound familiar?
Which idiom is characteristic of C++? Right: RAII (Resource Acquisition Is Initialization). RAII is the C++ way to implement the Proxy Pattern. Here are the facts about the Proxy Pattern.
- Provides a placeholder for accessing another object.
Also Known As
- Control access to another object
- Remote proxy (acts as an intermediary for a remote service)
- Virtual proxy (creates an object lazily on request)
- Security proxy (adds security to a request)
- Caching proxy (delivers cached requests)
- Controls the access and lifetime of the
- Supports the same interface as
- Defines the interface of the
- Implements the interface
The following examples use two generic proxies:
Both smart pointers can transparently access the member function
MyInt. It makes no difference if you call the member function
getValue on the
std::unique_ptr, (line 1) on the
std::shared_ptr, (line 2), or on the object directly. All calls return the same value:
The smart pointers model the Proxy Pattern in C++. Additionally, the RAII Idiom is the C++ adaption of the Proxy Pattern. RAII is the crucial idiom in C++. I will write more about it in a few lines.
- The Adaptor Pattern adjusts an existing interface, but the Facade creates a new simplified interface.
- The Decorator Pattern is structurally similar to the Proxy, but the Decorator has a different purpose. A Decorator extends an object with additional responsibilities. A Proxy controls access to an object.
- The Facade Pattern is similar to the Proxy because it encapsulates access to an object. The Facade does not support the same interface as the Proxy but supports a simplified one.
Pros and Cons
- The underlying object is fully transparent to the client.
- The proxy can answer requests directly without using the client
- The proxy can be transparently extended or replaced with another proxy.
- The separation of the proxy and the object makes the code more difficult
- The forwarded proxy calls may be performance critical
RAII stands for Resource Acquisition Is Initialization. The most crucial idiom in C++ is that a resource should be acquired in the constructor and released in the object’s destructor. The key idea is that the destructor will automatically be called if the object goes out of scope. Or, to put it differently: A resource’s lifetime is bound to a local variable’s lifetime, and C++ automatically manages the lifetime of locals.
There is one big difference between the Proxy Pattern and the RAII Idiom in C++. In the classical Proxy Pattern, the Proxy and the RealObject (object) implement the same interface. Therefore, you invoke a member function on the proxy, and this call is delegated to the object. On the contrary, it is typical for RAII to do the operation on the object implicitly.
The following example shows the deterministic behavior of RAII in C++.
ResourceGuard is a guard that manages its resource. In this case, the string stands for the resource. ResourceGuard creates in its constructor the resource and releases the resource in its destructor. It does its job very decent.
The destructor of resGuard1 (line 1) is called at the end of the main function (line 2). The lifetime of resGuard2 (line 3) already ends in line 4. Therefore, the destructor is automatically executed. Even the throwing of an exception does not affect the reliability of resGuard3 (line 5). The destructor is called at the end of the try block (line 6).
The screenshot shows the lifetimes of the objects.
It’s pretty easy to apply the RAII Idiom to make out the
All instances of
LockGuard share the same mutex
m. When an instance goes out of scope, it automatically unlocks its mutex
I wrote that the RAII Idiom is the most crucial idiom in C++. Let me name a few prominent examples.
Applications of RAII
- Containers of the STL, including
std::string: they automatically allocate in the constructor and deallocate in their destructor
- Smart Pointers:
std::shared_ptrtake ownership of the underlying raw pointer; they delete the underlying raw pointer if it is not needed anymore.
std::scoped_locklock in their constructor the underlying mutex and unlock it in their destructor automatically
std::jthreadin C++20 is an improved
std::jthreadautomatically joins in its destructor if necessary
In my next post, I will continue my journey through the patterns of the book “Design Patterns: Elements of Reusable Object-Oriented Software”. The Observer Pattern is a behavioral pattern that should be in the toolbox of each professional programmer.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,