C++ Core Guidelines: Comparison, Swap, and Hash

This post will be about comparisons, swap and hash. That means I conclude with his post my treatise about default operations rules in C++.

scales 310962 640 

Here are the nine rules.


Let's dive into the details.

Default operation rules:

C.80: Use =default if you have to be explicit about using the default semantics

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;
    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;
    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; }


C.81: Use =delete when you want to disable default behavior (without wanting an alternative)

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 {
    ~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

C.82: Don’t call virtual functions in constructors and destructors

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.

C.83: For value-like types, consider providing a noexcept swap function, C.84: A swap may not fail, and C.85: Make swap noexcept

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{     
  Cont& operator=(Cont&& rhs);
  int *pData;           

Cont& Cont::operator=(Cont&& rhs){
  std::swap(pData, rhs.pData);
  return *this;


C.86: Make == symmetric with respect of operand types and noexcept

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;
    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;
    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.

C.87: Beware of == on base classes

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 >=.

C.89: Make a hash noexcept

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, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, 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, Tornike Porchxidze, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Dimitrov Tsvetomir, Leo Goodstadt, Eduardo Velasquez, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, and Michael Young.


Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, and Rusty Fleming.



My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small



I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)


Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.


Contact Me

Modernes C++,


Tags: classes

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code


Today 6156

Yesterday 7646

Week 39451

Month 106117

All 7373957

Currently are 170 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments