我真的不明白这段代码的结果:
struct exampleClass
{
double a = 12.1;
std::map<int, double*> innerMap;
exampleClass()
{
std::cout << "ADR of variable a in constructor = " << &a << std::endl;
std::cout << "ADR of this in constructor = " << this << std::endl;
innerMap.emplace(4,&a);
}
};
int main(){
std::map<int, exampleClass> map;
map.insert(std::make_pair(4, exampleClass{}));
for (auto& it : map)
{
std::cout << "ADR of a = " << &(it.second.a) << std::endl;
std::cout << "Content of a = " << it.second.a << std::endl;
std::cout << it.second.innerMap.find(4)->second << std::endl;
std::cout << *(it.second.innerMap.find(4)->second); //the output is wrong
}
}
结果是:
构造函数中变量a的ADR = 0x7ffee080b500构造函数中的此ADR = 0x7ffee080b500A的ADR = 0x559ddb2c42e8a的内容= 12.10x7ffee080b5006.95312e-310
我不明白为什么for
循环中的地址与构造函数中的地址不同。此外,“构造函数地址”也用于插入innerMap
,这会导致错误。
有人可以向我解释吗?
另外令我困惑的是,以下各项按预期方式工作:
exampleClass abc{};
std::cout << "ADR of a = " << &(abc.a)<< std::endl;
std::cout << *(abc.innerMap.find(4)->second) << std::endl;
这里:
根据第一个答案,缺少自写的移动构造函数,因为std :: make_pair()调用了默认的移动构造函数,该构造函数不会处理特殊情况。下面的move构造函数将解决问题: