Apricot <yi**@21cn.co m> wrote in message news:<cb******* *************** **********@4ax. com>...
#include <iostream>
#include <string>
#include <map>
using namespace std ;
class tst
{
public :
tst() { cout << "tst::construct or" << endl ; }
tst(const tst & that) { cout << "tst::copy constructor" << endl ;
}
tst & operator =( const tst & that ) { cout << "tst::opera tor ="
<< endl ; }
~tst() { cout << "tst::destructo r" << endl ; }
} ;
int main()
{
map < string , tst > a ;
tst e ;
a.insert(pair < string , tst > ("standard", e) ) ;
system("pause") ;
return 0 ;
}
///// Output ////////////
tst::constructo r
tst::copy constructor
tst::copy constructor
tst::copy constructor
tst::destructor
tst::destructor
From what I understand all the STL containers get populated by
copying. This means that the only time the constructor gets called is
when you do
tst e;
a.insert(pair < string , tst > ("standard", e) );
First you create a (temporary) pair which gets populated by copying
("standard", e) into it.
In the second step the internal workings of the map implementation you
seem to be using creates a pair for internal use (2nd temporary in
this case) by copying ("standard", e) from the first pair into it.
Finally at the third step the map creates a node in the binary tree
that is populated by copying the 2nd temporary pair into it. (Note: it
is not required that any implementation uses a binary tree to store
map data, it just happens that all the implementations I know do it
that way)
fourth step is destroying the 2nd temporary pair (as seen by your
tst::destructor output), the one created by the insert action
fifth step is destroying the first temporary pair, the one you
explicitly created.
Hopefully the next bit of code can make it a bit clearer. replace your
main with it (it should also give you two more destructor calls).
-
int main()
-
{
-
{
-
map < string , tst > a;
-
cout << "map created\n" ;
-
tst e ;
-
cout << "tst e created\n" ;
-
std::pair<string, tst> mep("standard", e);
-
cout << "pair created\n";
-
a.insert(mep) ;
-
}
-
-
cout << "mash keyboard to continue" << endl;
-
cin.get();
-
return 0 ;
-
}
-