c++ - 为什么 map.insert() 方法调用复制构造函数两次?

标签 c++ map copy-constructor

我正在创建自定义类 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/

相关文章:

c++ - 复制构造函数的参数

c++ - C++中的前后自增/自减运算符在循环中是否具有相同的性能?

C++ "error: passing ' const std::map<int, std::basic_string<char>>' as ' this' argument of ..."

map - 去雾化 map

map - 在 Golang 中以 <value, key> 格式反转映射

c++ - 将初始化和已删除的拷贝构造函数(也称为不可复制对象)聚合为字段

c++ - 函数超出堆栈大小,考虑将一些数据移动到堆中 (C6262)

c++ - 即使每个线程都对自己的数据进行操作,是否有任何 cpp 函数或对象(不包括从 c 继承的)不是线程安全的?

php - 为 PHP 构建 Saxon/C 时出错

c++ - 试图读取充满对象的 vector 的访问冲突