stl map - could any one explain the o/p

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class tst
{
   public:
      tst() {
         cout<<"ctor tst()\n";
      }
      tst(const tst& ob) {
         cout<<"cp ctor tst()\n";
      }
      ~tst()
      {
         cout<<"dtor tst()\n";
      }
};
map<string,tst> mp;
int main(void)
{
   mp["111"];
   //mp["111"]=tst();
}

output:
1
2
3
4
5
6
ctor tst()
cp ctor tst()
cp ctor tst()
dtor tst()
dtor tst()
dtor tst()

map's index operator creates an entry if one doesn't already exist. That's why there are find and insert operators.
Could u explain why ctor is called three times?
Can anyone explain where can i get mangoes?
That's just how std::map works. It can't be explained without opening up the implementation and seeing what's going on.
1
2
3
4
5
6
7
8
9
10
11
12
      mapped_type&
      operator[](const key_type& __k)
      {
	// concept requirements
	__glibcxx_function_requires(_DefaultConstructibleConcept<mapped_type>)

	iterator __i = lower_bound(__k);
	// __i->first is greater than or equivalent to __k.
	if (__i == end() || key_comp()(__k, (*__i).first))
          __i = insert(__i, value_type(__k, mapped_type()));
	return (*__i).second;
      }


mapped_type() = first call to non-copy constructor.
value_type( __k, mapped_type() ) = first call to copy constructor, to make a std::pair<> out of key and value.
insert( ... ) = second call to copy constructor, to copy std::pair into the container.


[EDIT: borrowed code from gcc...]
Last edited on
Thanks
Topic archived. No new replies allowed.