gpt4 book ai didi

c++ - 返回本地 map 数据的“幸运”有效指针数据?

转载 作者:可可西里 更新时间:2023-11-01 17:50:35 27 4
gpt4 key购买 nike

在我的 C++ 程序中,我有一个函数返回一个包含元素的映射,每个元素都可以有一个指向映射中另一个元素的指针。我在函数末尾返回 map 之前设置了这些指针。示例代码:

#include <iostream>
#include <map>
#include <string>

class TestObject{
public:
TestObject(std::string message) : message(message), other(nullptr){}

TestObject* other;
std::string message;
};

std::map<std::string, TestObject> mapReturningFunction(){
std::map<std::string, TestObject> returnMap;

TestObject firstObject("I'm the first message!");

returnMap.insert(std::make_pair("first", firstObject));

TestObject secondObject("I'm the second message!");
returnMap.insert(std::make_pair("second", secondObject));

TestObject* secondObjectPointer = &(returnMap.at("second"));
returnMap.at("first").other = secondObjectPointer;

return returnMap;
}

int main(){
std::map<std::string, TestObject> returnedMap = mapReturningFunction();

std::cout << returnedMap.at("first").other->message << std::endl; // Gives a valid message every time

std::cin.get();

return 0;
}

在函数的调用点,指针 other 仍然有效,尽管我怀疑它会变得无效,因为“指向对象”的函数内部映射是的元素超出范围。

这个和Can a local variable's memory be accessed outside its scope?里面说的基本一样吗?我基本上是“幸运的”指针仍然指向有效数据?或者发生了什么不同的事情?

我真的认为每次都是“幸运”命中,但如果能得到确认就更好了。

最佳答案

是的,你很“幸运”(没那么幸运,你的程序迟早会崩溃或以某种方式做坏事)。


解释:

returnMap 在堆栈上分配:当 mapReturningFunction 返回时它将被销毁。

您获取 map 内对象的地址并将其分配为 other 指针。

当您的函数返回时,returnMap 被复制到返回值,因此(复制的)指针现在真正指向垃圾。

优化器通常会避免最后一次复制,它称为“复制省略”(或 "Return Value Optimization")并且可能是您“正常”行为的原因。不过没关系,你的程序有未定义的行为

关于c++ - 返回本地 map 数据的“幸运”有效指针数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166842/

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