Need some help understanding using a C ++ map as an associative array

I went through Josuttis "Using Map as Associative Arrays" (from the C ++ Standard Library - Tutorial and Reference, 2nd edition ) and came across Using std :: map as an associative array in Stack Overflow. Now I have more questions about the constructors that are called when inserted into the map.

Here is my sample program (not using the best encoding methods, please excuse me for this):

class C
{
public:

   string s;

   C() { cout << "default " << endl;}

   C(const string& p) : s(p)
   { cout << "one param" << endl;}

   C(const C& obj)
   {
       if (this != &obj)
       {
         s = obj.s;
       }
       cout << "copy constr" << endl;
   }

   C& operator  = (const C& obj)
   {
       if (this != &obj)
       {
             s = obj.s;
       }
      cout << "copy initializer" << endl;
      return *this;
   }
};

int main()
{
    map<int,C> map1;
    C obj("test");

    cout << "Inserting using index" << endl;
    map1[1] = obj;

    cout << "Inserting using insert / pair" << endl;
    map1.insert(make_pair(2,obj));
}

The output for this program:

one param
Inserting using index
default
copy constr
copy constr
copy initializer
Inserting using insert / pair
copy constr
copy constr
copy constr
copy constr

I assumed that initializing the map by index should call the default constructor and it is followed by an assignment operator.

But execution map1[1] = objproduces the following output:

Inserting using index
default
copy constr
copy constr
copy initializer

- ?

+5
4

std:: map, , [] ( )

(*((this->insert(make_pair(1,C()))).first)).second

, , . C(). make_pair, C. , , C. , , , .

+7

. :

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

class C
{
    public:
        string s;
        C()
        {
            cout << "default " << endl;
        }
        C(const string& p)
        : s(p)
        {
            cout << "one param(" << s << ")" << endl;
        }
        C(const C& obj)
            :s(obj.s)
        {
           cout << "copy constr(" << s << ")" <<endl;
        }
        C& operator  = (const C& obj)
        {
            cout << "copy initializer\t" <<;

            C copy(obj);
            std::swap(s,copy.s);

            return *this;
        }
};

int main()
{
    map<int,C> map1;
    cout << "Inserting using index" << endl;
    map1[1] = C("Plop");
}

, .
, ​​ .

Inserting using index
default
copy constr()
copy constr()
one param(Plop)
copy initializer      copy constr(Plop)
+2

What happens if you just do it map[1];? This may include internal copies, depending on the implementation of the mapstandard library used.

0
source

Will actually map1[1] = objcreate the pairfirst

0
source

All Articles