我有一个 std::unordered_map ,我发现我插入其中的对象与我通过使用范围遍历从中获得的对象不同。
我怀疑这里可能发生了一些对象复制,但是在我向复制构造函数添加了一些转储之后,它根本没有被调用。
谁能告诉我插入和遍历 std::unordered_map 时后台发生了什么?
我尝试了以下代码并转储:
[结果]
mypair constuctor
mypair constuctor
string1 address:0x7ffccb813ba0
string2 address:0x7ffccb813bd0
++++++++++++++++
auto &x address:0x55fb40529378
string2: 0.5
auto &x address:0x55fb405292c8
string1: 0.3
++++++++++++++++
auto x address:0x7ffccb813c00
string2: 0.5
auto x address:0x7ffccb813c00
string1: 0.3
++++++++++++++++
Run Code Online (Sandbox Code Playgroud)
[来源]
#include <iostream>
#include <string>
#include <unordered_map>
class mypair : public std::pair<std::string,double> {
public:
mypair(std::string str, double num):std::pair<std::string,double>(str, num) {
std::cout<<"mypair constuctor"<<std::endl;
}
mypair( const mypair& ) {
std::cout<<"mypair copy constuctor"<<std::endl;
}
mypair& operator=(const mypair&) {
std::cout<<"mypair copy assignment"<<std::endl;
return …Run Code Online (Sandbox Code Playgroud)