An idiom is an architectural or design pattern implementation in a concrete programming language. Applying them is idiomatic for a programming language. Today. I write about the Copy-and-Swap Idiom in C++. This idiom gives you the strong exception safety guarantee.
Before I write about the Copy-and-Swap Idiom, I should first clarify the strong exception safety guarantee. Here are a few general thoughts about error handling:
When you handle an error, the following aspects should be considered:
- Detect an error
- Transmit information about an error to some handler code
- Preserve the valid state of a program
- Avoid resource leaks
Abrahams Guarantees describe a contract that is fundamental if you think about exception safety. Here are the four levels of the contract:
- No-throw guarantee, also known as failure transparency: Operations are guaranteed to succeed and satisfy all requirements, even in exceptional situations. If an exception occurs, it is handled internally and cannot be observed by clients.
- Strong exception safety, also known as commit or rollback semantics: Operations can fail, but failed operations are guaranteed to have no side effects, so all data retain their original values.
- Basic exception safety, also known as a no-leak guarantee: Partial execution of failed operations can cause side effects, but all invariants are preserved, and there are no resource leaks (including memory leaks). Any stored data contains valid values, even if they differ from what they were before the exception.
- No exception safety: No guarantees are made.
In general, you should at least aim for the basic exception safety guarantee. This means that you don’t have resource leaks in case of an error, and your program is always in a well-defined state. If your program is not in a well-defined state after an error, there is only one option left: shut down your program.
I stated that the Copy-and-Swap Idiom provides a strong exception safety guarantee. This is a stronger guarantee such as the basic exception safety guarantee.
The Copy-and-Swap Idiom
Okay, I know what copy means. Therefore, let me write about swap:
For a type to be a regular type, it has to support a
swap function. A more informal definition of regular type is a value-like type that behaves like an
int. I will write about regular types in an upcoming post. According to the rules “C.83: For value-like types, consider providing a noexcept swap function” and “C.85: Make swap noexcept” of the C++ Core Guidelines, a
swap function should not fail and be
The following data type Foo has a
For convenience reasons, you should consider supporting a non-member swap function based on the already implemented swap member function.
If you do not provide a non-member
swap function, then the standard library algorithms that require swapping (such as
std::rotate) will fall back to the
std::swap template, which is defined in terms of move construction and move assignment.
The C++ standard offers more than 40 overloads of
std::swap. You can use the
swap function as a building block for many idioms, such as copy construction or move assignment.
This brings me to the Copy-and-Swap Idiom.
If you use the Copy-and-Swap Idiom to implement the copy assignment and the move assignment operator, you must define your own swap — either as a member function or as a friend. I added a
swap function to the class
Cont and used it in the copy assignment and move assignment operator.
Both assignment operators make a temporary copy
tmp of the source object (lines 1 and ) and then apply the
swap function to it (lines 3 and 4). When the used
swap functions are
noexcept, the copy assignment operator and the move assignment operator support the strong exception safety guarantee. This means that both assignment operators guarantee that the operations call will be fully rolled back in case of an error such as the error never happened.
Operations supporting the Copy-and-Swap Idiom allow you to program in a transaction-based style. You prepare an operation (working on the copy) and publish the operation (swap the result) when it is fine. The Copy-and-Swap Idiom is a very powerful idiom that is applied pretty often.
- Concurrent programming: You make your modification on a local object. This is, by definition, thread-safe because the data is not shared. When you are done with your change, you overwrite the shared data with your local data in a protected way.
- Version control system: First, you check out the data and get a local copy. When you are done with your change, you commit your change and have to handle merge conflicts eventually. In case you cannot solve the merge conflict, you throw away your local change and check out once more.
swap function is based on copy semantics instead of move semantics, a
swap function may fail because of memory exhaustion. The following implementation contradicts the C++ Core Guidelines rule “C++94: A
swap function must not fail“.This is the C++98 implementation of
In this case, memory exhaustion may cause a
Partial Function Application is a technique in which a function binds a few of its arguments and returns a function taking fewer arguments. This technique is related to a technique used in functional languages called currying.
A Short Break
I will make a short two weeks Christmas Break. My next post will be published on Monday, the 9th of January. Have a good time,
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, Marco Parri Empoli, moon, and Philipp Lenk.
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
|My special thanks to SHAVEDYAKS
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
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++
Online Seminars (German)
- C++20: Get the Details (2. Apr 2024 bis 4. Apr 2024)
- Clean Code: Best Practices für modernes C++ (21. Mai 2024 bis 23. Mai 2024)
Programmierung mit modernem C++ (2. Jul 2024 bis 4.
- 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,