对stl map 赋值添加元素的疑惑 求解(管理员让这个帖子多见会人吧~~谢谢啦!)

今天看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?

哪位对这个流程比较熟悉~^_^

原文地址:https://www.cnblogs.com/ziyoudefeng/p/2429149.html