map + copy constructor

Hi Guys,

In the code below, why is copy constructor called three times?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

class base { 
    
    public:
        base& operator=(const base&) { 
            cout<<"operator="<<endl; 
        }   
    
        base(const base&) { 
            cout<<"copy constructor"<<endl; 
        }   
        base() { 
        }   
        int i;
} ; 

int main() { 

    map<int,base> mm; 
    base obj ;
    obj.i = 10; 
    mm.insert(pair<int,base>(1,obj)) ; 

    return 0;
}



copy constructor
copy constructor
copy constructor
Using GNU's implementation in libstdc++-2.90.8:

1. The pair itself copies each of its parameters:
1
2
3
4
5
6
7
8
9
10
template <class _T1, class _T2>
struct pair {
  typedef _T1 first_type;
  typedef _T2 second_type;

  _T1 first;
  _T2 second;
  pair() : first(_T1()), second(_T2()) {}
  pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) {}
  //... 


2. The map implementation uses a red-black tree class that eventually calls construct:
1
2
3
4
template <class _Tp1, class _Tp2>
inline void construct(_Tp1* __p, const _Tp2& __value) {
  new (__p) _Tp1(__value);
}

I'm not very clear on what is going on with line 3, but I'm guessing _Tp1(__value) is calling the copy constructor...

I didn't find the third one in the few minutes that I've been looking but it might have something to do with the tree re-balancing (although it looked like it used assignment for that).
Last edited on
I'm guessing there is a conversion operation in there somewhere because you are not using your map's built-in typedefs.

Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main() { 

    typedef map<int,base> MyMap;

    MyMap mm;
    base obj;

    obj.i = 10;
    MyMap::value_type p(1, obj);
    mm.insert(p);

    return 0;
}



Thanks for the explanation guys !
Topic archived. No new replies allowed.