今天看C++ 標准程序庫里面講到說map[key] = value;這種方式效率低,原因是新元素必須先使用default構造函數將實值(value)初始化,而這個初值馬上又被真正的value給覆蓋了。然后就想自己測試一下,下面是自己的測試代碼,然后后面有自己對運行結果的不解。
1、定義一個value型別,供map中使用
1 #pragma once 2 #include <iostream> 3 4 class TestMapSec 5 { 6 public: 7 TestMapSec(void) { std::cout << "default constructor!" << std::endl; } 8 TestMapSec(int i) : _i(i) { std::cout << "one-parameter constructor!!" << std::endl; } 9 TestMapSec( const TestMapSec& rhs ) : _i(rhs._i) { std::cout << "copy constructor!!" << std::endl; } 10 ~TestMapSec(void) { std::cout << "destructor!!" << std::endl; } 11 void operator=( const TestMapSec& rhs ) { _i = rhs._i; std::cout << "assignment!!" << std::endl; } 12 int get() { return _i; } 13 14 private: 15 int _i; 16 };
2、主main測試程序
1 // StandLibP202.cpp : 定義控制台應用程序的入口點。
2 //
3
4 #include "stdafx.h"
5 #include <map>
6 #include <iostream>
7 #include <string>
8 #include "TestMapSec.h"
9 using namespace std;
10
11 int _tmain(int argc, _TCHAR* argv[])
12 {
13
14 TestMapSec t(5);
15 cout << "1-------" << endl;
16 typedef map<string, TestMapSec> StringFloatMap;
17 cout << "2-------" << endl;
18 StringFloatMap _map;
19 cout << "3-------" << endl;
20 _map["key"] = t;
21 cout << "4-------" << endl;
22
23 cout << _map["key"].get() << endl;
24
25
26 return 0;
27 }
下面是運行結果:
one-parameter constructor!!
1-------
2-------
3-------
default constructor!
copy constructor!!
copy constructor!!
destructor!!
destructor!!
assignment!!
4-------
5
destructor!!
destructor!!
請按任意鍵繼續. . .
也就是說第20行代碼_map["key"] = t;會調用兩次拷貝構造,然后析構,最后再拷貝。這里就不理解了為什么有兩次copy constructor?
哪位對這個流程比較熟悉~^_^