jeudi 27 juin 2019

insert const pair vs non-const pair vs non-const key to unordered_map

I watch this CppCon video: https://youtu.be/ncHmEUmJZf4?t=2284 (time 38:04)

I don't understand what is the different between calling:

std::pair<iterator,bool> insert( const value_type& value );

and

std::pair<iterator,bool> insert( value_type&& value );

I wrote my own code, and looks like in both cases this same constructor was called.

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

struct A
{
  A() noexcept                      {cout << "A()" << endl; }
  A(const A&) noexcept              {cout << "A(const A&)" << endl;}
};


int main()
{
    unordered_map<int, A> m;
    const pair<const int, A> p = {}; //first case OK
    //pair<const int, A> p = {};    //second case NOK
    //const pair<int, A> p = {};    //third case NOK
    cout << "---------" << endl;
    {
        m.insert(p);
        m.insert(p);
        m.insert(p);
        m.insert(p);
    }
    cout << "---------" << endl;
}

Output for first case:

A()
---------
A(const A&)
---------

Output for second and third case:

A()
---------
A(const A&)
A(const A&)
A(const A&)
A(const A&)
---------

1) Why pair must be const to don't make a copy? (second case)

2) Why key must be const to don't make a copy (unordered_map's key in definition is non-const)? (third case)

Aucun commentaire:

Enregistrer un commentaire