The original std::map where your original TileInfo
objects are stored is here:
map<int,TileInfo> tmpInfo;
for(unsigned int i = 0; i < 3; i++)
{
tmpInfo.insert(pair<int,TileInfo>(i,TileInfo(i,"testname")));
}
That is the map the houses the pairs. you then make a copy of said map. It creates copies of all your TileInfo
objects, which is ok.
Map rtrnVal = Map(tmpInfo);
But this is where the wheels begin to come off. You fire loadTiles
here, which sets up your map of vectors that addres the relative TileInfo
objects in rtrnVal
. This code:
rtrnVal.loadTiles();
leads to this code. Note that you're pushing the addresses of your mapped TileInfo
objects into your vectors. The map where these reside is this objects map.
void Map::loadTiles()
{
for(unsigned int i = 0; i < 3; i++)
{
vector <Tile> line;
for(unsigned int j = 0; j < 3; j++)
{
map<int,TileInfo>::iterator ite = tileInfo.find(i);
if( ite!=tileInfo.end())
line.push_back(Tile(&(ite->second)));
else
{
line.push_back(Tile(NULL));
}
}
tiles.push_back(line);
}
}
Finally, back where we started you do this:
return rtrnVal;
This makes a copy of the Map
, which makes a copy of the map of vectors, which contain pointers to the TileInfo
in the map within rtrnVal
that is about to be destroyed on function exit. The result back on the caller side.
Map newMap = createMap();
newMap
now holds dangling pointers to TileInfo
objects that were in rtrnVal
in createMap
.
Possible Solution
Rather than having a map of vectors containing pointers to TileInfo
s, consider a map of vectors of indexes, where each index keys to a 0-based slot in a TileInfo
std::vector
that is contained along side the map. I can see what you were trying to do (singular TileInfo
s shared across multiple cells) so you still reap that benefit. The vector will come along for the ride wherever the map does (they're owned by the same Map
object) and copying won't harm anything because both the map (of indexes) and the vector (of TileInfo
) will copy safely. In the end you still get what you want (singular TileInfo
s) but now-indexed by number rather than pointer. As a bonus, you don't have to deal with rebasing pointers to TileInfo from one map to another in a custom copy-ctor. Its all relative (0.. n-1)
Best of luck.