【发布时间】:2014-08-06 17:47:41
【问题描述】:
在我的 C++ 程序中,我有一个函数,它返回一个包含元素的映射,每个元素都可以有一个指向映射中另一个元素的指针。我在函数末尾返回地图之前设置了这些指针。示例代码:
#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?中提到的基本相同吗?我基本上'幸运'指针仍然指向有效数据?还是发生了一些不同的事情?
我确实认为每次都是“幸运”命中,但如果有一些确认会非常好。
【问题讨论】:
-
如果不执行 NRVO,则返回的映射将包含指向已释放内存的指针。
标签: c++