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.
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 methods you have to define all of them.
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.
class Tracer {
string message;
public:
Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
~Tracer() { cerr << "exiting " << message << '\n'; }
Tracer(const Tracer&) = default;
Tracer& operator=(const Tracer&) = default;
Tracer(Tracer&&) = default;
Tracer& operator=(Tracer&&) = default;
};
That was easy! Right? But I can also do it by myself which is at least boring but is also error-prone.
class Tracer2 {
string message;
public:
Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
~Tracer2() { cerr << "exiting " << message << '\n'; }
Tracer2(const Tracer2& a) : message{a.message} {}
Tracer2& operator=(const Tracer2& a) { message = a.message; return *this; }
Tracer2(Tracer2&& a) :message{a.message} {}
Tracer2& operator=(Tracer2&& a) { message = a.message; return *this; }
};
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 stranges types. Instances of Immortal cannot be destructed.
class Immortal {
public:
~Immortal() = delete; // do not allow destruction
// ...
};
void use()
{
Immortal ugh; // error: ugh cannot be destroyed
Immortal* p = new Immortal{};
delete p; // error: cannot destroy *p
}
This rule is quite similar to the 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.
A swap function is quite handy.
template< typename T >
void std::swap(T & a, T & b) noexcept {
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}
The C++ standard offers more than 40 specialisations for std::swap. You can use it as a building block for a lot of idioms such as copy construction/assignment. A swap function should not fail; therefore, you have to declare it as noexcept.
Here is an example of a move assignment operation using std::swap. pdata points to an array.
class Cont{
public:
Cont& operator=(Cont&& rhs);
private:
int *pData;
};
Cont& Cont::operator=(Cont&& rhs){
std::swap(pData, rhs.pData);
return *this;
}
If you don't want to surprise your user, you should make the == operator symmetric.
Here is a unintuitive == operator which is defined inside the class.
class MyNumber {
int num;
public:
MyNumber(int n): num(n){};
bool operator==(const MyNumber& rhs) const { return num == rhs.num; }
};
int main(){
MyNumber(5) == 5;
// 5 == MyNumber(5);
}
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.
class MyNumber {
int num;
public:
MyNumber(int n): num(n){};
bool operator==(const MyNumber& rhs) const { return num == rhs.num; }
friend bool operator==(const int& lhs, const MyNumber& rhs){
return lhs == rhs.num;
}
};
int main(){
MyNumber(5) == 5;
5 == MyNumber(5);
}
The surprises continue.
Writing a foolproof == operator for a hierarchy is hard. The guidelines gives a nice example for such a hard job. Here is the hierarchy.
class B {
string name;
int number;
virtual bool operator==(const B& a) const
{
return name == a.name && number == a.number;
}
// ...
};
class D :B {
char character;
virtual bool operator==(const D& a) const
{
return name == a.name && number == a.number && character == a.character;
}
// ...
};
Let's try it out.
B b = ...
D d = ...
b == d; // compares name and number, ignores d's character // (1)
d == b; // error: no == defined // (2)
D d2;
d == d2; // compares, name, number, and character
B& b2 = d2;
b2 == d; // compares name and number, ignores d2's and d's character // (1)
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 have to define a hash function for the key.
Do it by using the std::hash function for the attributes of your class and combine them with ^ (xor).
struct MyKey{
int valInt = 5;
double valDou = 5.5;
};
struct MyHash{
std::size_t operator()(MyKey m) const {
std::hash<int> hashVal1;
std::hash<double> hashVal2;
return hashVal1(m.valInt) ^ hashVal2(m.valDou);
}
};
What's next?
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, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Wolfgang Gärtner, Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Avi Kohn, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, and Tornike Porchxidze.
Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, and Richard Sargeant.
My special thanks to Embarcadero 
Seminars
I'm happy to give online-seminars or face-to-face seminars world-wide. Please call me if you have any questions.
Bookable (Online)
Deutsch
English
Standard Seminars
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
New
Contact Me
- Tel.: +49 7472 917441
- Mobil: +49 152 31965939
- Mail: This email address is being protected from spambots. You need JavaScript enabled to view it.
- German Seminar Page: www.ModernesCpp.de
- English Seminar Page: www.ModernesCpp.net
Modernes C++,

Read more...