我正在创建自定义类 Node
为了使用 map<int,Node>
实现二叉树容器:int
map 的关键是 Node
的标识符目的。在类里面Node
我必须实现一个复制构造函数。
插入 Node
时 map 上的对象,我注意到 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()
最佳答案
很可能是因为您的 map 的值类型是 pair<int const, Node>
, 不是 pair<int, Node>
: 在映射中,键是常量。
自 insert()
接受 pair<int const, Node> const&
然后你提供一个pair<int, Node>
,要执行转换,必须构造一个临时值,映射中的值可以从中依次复制构造。
要验证它,请更改此行:
pair<int, Node> toInsert = pair<int, Node>(2, node2);
进入这一行:
pair<int const, Node> toInsert = pair<int const, Node>(2, node2);
您应该会看到对复制构造函数的额外调用消失了。
另请记住,标准库容器的具体实现不需要执行特定数量的拷贝:实现可能会有所不同,不同的优化级别也会使事情有所不同。
关于c++ - 为什么 map.insert() 方法调用复制构造函数两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15247262/