In my C++ program I have a function that returns a map containing elements that each can have a pointer to another element in the map. I set these pointers before returning the map at the end of the function. Example code:
#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;
}
At the call-site of the function, the pointer other
is still valid, even though I suspected it would become invalid because the map inside the function of which the 'pointed-to object' is an element of goes out of scope.
Is this basically the same as mentioned in Can a local variable's memory be accessed outside its scope? ? I'm basically 'lucky' the pointer is still pointing to valid data? Or is something different going on?
I really do think it is a 'lucky' hit every time, but some confirmation would be very nice.