我正在创建自定义类Node
以便使用map<int,Node>
容器实现二叉树:映射的int
键是Node
对象的标识符。在类Node
我不得不实现一个复制构造函数。为什么map.insert()方法调用拷贝构造函数两次?
当在地图上插入一个Node
对象时,我注意到Node
的复制构造函数被调用两次。为什么?
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);
运行上面的代码,输出如下:
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()
哪里是副本#3你的解释? OP的帖子显示了toInsert(你解释过)的一个副本,以及两个插入副本(你只能解释一个副本)。另外,我不认为你对第二部分的解释是正确的。容器制作副本并插入它们的原因是设计上的(即它们保证你这样做,以便你的对象在插入范围内保持原状),而不是因为生命的原因。如果你不想要,你可以使用'emplace'或'std :: move'。 – us2012 2013-03-06 12:37:58
好笑,看来我误解了这个问题。那么,我现在也从已接受的答案中学到了一些东西。好吧。 – Bingo 2013-03-06 12:40:08