This post will be about comparisons, swap, and hash. That means I conclude with his post my treatise about default operations rules in C++.
Here are the nine rules.
- C.80: Use
=defaultif you have to be explicit about using the default semantics
- C.81: Use
=deletewhen you want to disable default behavior (without wanting an alternative)
- C.82: Don’t call virtual functions in constructors and destructors
- C.83: For value-like types, consider providing a
- C.84: A
swapmay not fail
- C.85: Make
- C.86: Make
==symmetric with respect of operand types and
- C.87: Beware of
==on base classes
- C.89: Make a
Let’s dive into the details.
Default operation rules:
Do you remember the rule of five? It means if you define one of the five special member functions, you must define all.
Here is the point.
When I implement the destructor, such as in the following example, I have to define the copy and move constructor and assignment operator.
That was easy! Right? But I can also do it alone, which is at least uninteresting and error-prone.
Sometimes, you want to disable the default operations. Here comes delete into the play. C++ eats its own dog food. The copy constructor of types such as locks, mutexes, promises, or futures is set to delete. The same holds true for the smart pointer std::unique_ptr: std::unique_ptr(const std::unique_ptr&) = delete.
You can use delete to create strange types. Instances of Immortal cannot be destroyed.
This rule is quite similar to rule C.50: Use a factory function if you need “virtual behavior” during initialization which I presented in the post C++ Core Guidelines: Constructors.
The next three rules are about swap functions. Let’s do it together.
C.83: For value-like types, consider providing a
noexcept swap function, C.84: A
swap may not fail, and C.85: Make
A swap function is quite handy.
The C++ standard offers more than 40 specializations for std::swap. You can use it as a building block for many idioms, such as copy construction/assignment. A swap function should not fail; therefore, you must declare it as noexcept.
Here is an example of a move assignment operation using std::swap. pdata points to an array.
If you don’t want to surprise your user, you should make the == operator symmetric.
Here is an unintuitive == operator, which is defined inside the class.
The call MyNumber(5) == 5 is valid because the constructor converts the int argument to an instance of MyNumber. The last line gives an error. The comparison operator for natural numbers will not accept an instance of MyNumber.
The elegant way to solve this asymmetry is to declare a friend
operator== inside the class MyNumber. Here is the second version of MyNumber.
The surprises continue.
Writing a foolproof == operator for a hierarchy is hard. The guidelines give an excellent example of such a challenging job. Here is the hierarchy.
Let’s try it out.
Comparing instances of B or instances of D will work. But mixing instances of B and D will not work as expected. Using B’s == operator ignores D‘s character (1). Using D‘s operator will not work for instances of B (3). The last line is quite tricky. The == operator of B is used. Why? The == operator of D overwrote the == operator of B.Really? No! Both operators have different signatures. One taking an instance of B; the other taking an instance of D. D‘s version will not overwrite B‘s version.
This observation will also hold for the other five comparison operators: !=, <, <=, >, and >=.
Hash functions are implicitly used by unordered associative containers such as std::unordered_map. The user doesn’t expect that they will throw. If you want to use your own type as a key in an unordered associative container, you must define a hash function for the key.
Do it by using the std::hash function for the attributes of your class and combining them with ^ (xor).
Following the guidelines, the next topic should be containers and other resource handles, but only the names of the rules are available. Therefore I will skip this part and go straight to lambda expressions in the next post.
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, and Bhavith C Achar.
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,