为什么map.insert()方法两次调用复制构造函数? [英] Why does the map.insert() method invoke the copy constructor twice?
问题描述
我正在创建自定义类 Node
,以便使用 map< int,Node>
容器实现二进制树: int
键是 Node
对象的标识符.在类 Node
中,我必须实现一个复制构造函数.
在地图上插入 Node
对象时,我注意到 Node
的副本构造函数被调用了两次.为什么?
cout<<"node2"<<恩德尔节点node2;node2.set_depth(2);node2.make_it_branch(3,4);cout<<地图"<<恩德尔map< int,Node>映射cout<<"toInsert"<<恩德尔对< int,节点>toInsert = pair< int,Node>(2,node2);cout<<插入"<<恩德尔mapping.insert(toInsert);
运行上面的代码,输出如下:
node2--- Node()地图插入---节点(const Node& orig)插--- Node(const Node& orig)//为什么复制构造函数被调用两次?---节点(const Node& orig)//-------------------------------------------------〜Node()-〜Node()-〜Node()-〜Node()
最有可能是因为您地图的值类型是 pair< int const,Node>
,而不是 pair< int,Node>
:在地图中,键为恒定.
因为 insert()
接受 pair< int const,Node>const&
,然后提供 pair< int,Node>
,以执行转换,必须构造一个临时文件,然后可以从该临时文件中复制地图中的值.>
要进行验证,请更改以下行:
pair< int,Node>toInsert = pair< int,节点>(2,节点2);
进入此行:
pair< int const,Node>toInsert = pair< int const,Node>(2,node2);
您应该看到对复制构造函数的额外调用消失了.
还请记住,执行特定数量的副本不需要标准库容器的具体实现:实现可能会有所不同,并且不同的优化级别也会使事情有所不同.
I'm creating the custom class Node
in order to implement a binary tree using a map<int,Node>
container: the int
key of the map is the identifier of a Node
object. In the class Node
I had to implement a copy constructor.
When inserting a Node
object on the map, I noticed that the copy constructor of the Node
is invoked twice. Why?
cout << "node2" << endl;
Node node2;
node2.set_depth(2);
node2.make_it_branch(3,4);
cout << "map" << endl;
map<int,Node> mapping;
cout << "toInsert" << endl;
pair<int,Node> toInsert = pair<int,Node>(2,node2);
cout << "insert" << endl;
mapping.insert(toInsert);
Running the above code, the output is as follows:
node2
--- Node()
map
toInsert
--- Node(const Node& orig)
insert
--- Node(const Node& orig) // Why does the copy constructor be invoked twice?
--- Node(const Node& orig) // ------------------------------------------------
--- ~Node()
--- ~Node()
--- ~Node()
--- ~Node()
Most likely because the value type of your map is pair<int const, Node>
, not pair<int, Node>
: in a map, the key is constant.
Since insert()
accepts a pair<int const, Node> const&
and you supply a pair<int, Node>
, to perform the conversion a temporary must be constructed from which the value in the map can in turn be copy-constructed.
To verify it, change this line:
pair<int, Node> toInsert = pair<int, Node>(2, node2);
Into this line:
pair<int const, Node> toInsert = pair<int const, Node>(2, node2);
And you should see the extra call to the copy constructor disappear.
Also keep in mind, that the concrete implementation of Standard Library containers are not required to perform a particular number of copies: implementations may vary, and different optimization levels could make things different as well.
这篇关于为什么map.insert()方法两次调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!