gpt4 book ai didi

c++ - 将对象插入 std::map 时构造函数中变量的地址

转载 作者:行者123 更新时间:2023-11-28 01:17:31 26 4
gpt4 key购买 nike

我真的不明白这段代码的结果:

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
}
}

结果是:

ADR of  variable a in constructor = 0x7ffee080b500 ADR of this in constructor = 0x7ffee080b500ADR of a = 0x559ddb2c42e8Content of a = 12.10x7ffee080b5006.95312e-310

I do not understand why the addresses in the for loop differ from the addresses in the constructor. Also the "constructor address" is used for inserting in the innerMap, which causes a bug.

Can someone explain this to me?

What confuses me additionally is that the following works as expected:

exampleClass abc{};
std::cout << "ADR of a = " << &(abc.a)<< std::endl;
std::cout << *(abc.innerMap.find(4)->second) << std::endl;

最佳答案

这里:

map.insert(std::make_pair(4, exampleClass{}));

exampleClass 的临时实例已创建,exampleClass::innerMap 正确指向该实例的 exampleClass::a。但是,紧接着,它被四处移动 - 通过对进入 mapexampleClass::innerMap的内容保持不变,即映射到4的指针是相同的,但是在临时实例消失后,它就失效了。

解决方案:在遵守 the rules of three/five 的同时修复类的复制/移动构造函数的语义.您唯一能弄清楚的是对这些指针到处使用 new/delete。但我们不那样做。如果 a 是该类的所有实例之间共享的默认值,则它应该是 static。这样,它就会比所有实例都长寿,并且这个问题将不存在。否则,使用智能指针。

关于c++ - 将对象插入 std::map 时构造函数中变量的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com