neodreamerus 发表于 2016-07-25 09:08

stl map中插入操作要构造三次对象??

我写了下面简单的测试代码,发现STL map中插入操作需要构造三个对象,其中两个是临时对象,第三个才是放在容器里的。
请问构造两个临时对象的目的是什么,谢谢。
#include <iostream>
#include <map>
#include <vector>

using namespace std;

struct A {

    A() {
      cout << "default ctor" << endl;
    }

    A(const A&) {
      cout << "copy ctor" << endl;
    }

    A& operator=(const A&) {
      cout << "assignment" << endl;
    }

    ~A() {
      cout << "dtor" << endl;
    }

};

int main(void) {

    map<int, A> a;
    a;
    return 0;
}

lxyscls 发表于 2016-07-25 09:53

回复 1# neodreamerus # g++ -o map map.cpp --std=c++11
# ./map
default ctor
dtor
# g++ -o map map.cpp
# ./map            
default ctor
copy ctor
copy ctor
dtor
dtor
dtor
#

windoze 发表于 2016-07-25 13:32

这是C++里一处著名的傻B景观,map的[]操作符居然是mutating……

neodreamerus 发表于 2016-07-26 11:29

回复 2# lxyscls

刚才试了一下,加了c++11确实结果不同。


   

cjfeii 发表于 2016-07-28 11:30

差别怎么这么大。。。。。。。。
页: [1]
查看完整版本: stl map中插入操作要构造三次对象??