wrote:
> I have some code that needs to declare an STL Map in the static scope,
> insert values into the map in the function of one class and access the
> values in the functions of other classes. This seems like a pretty
> straight forward request, but when I implement it I get either garbage
> data when I try to access it or I get an Access Violation runtime
> error (depending on the state of my code while I try to figure out how
> to get this rediculously simple idea to work). What the heck?! What
> am I doing wrong? Here is some sample code that gives an Access
> Violation:
>
> typedef struct _ShipType {
> int a;
> int b;
> int c;
> } ShipType;
>
> static std::map<int, ShipType *> shipTypeMap;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I can only think that you're seeing this in more than one compilation unit.
>
> void GameLoader::LoadGame()
> {
> shipTypeMap[0] = new ShipType();
> shipTypeMap[0]->a = 1;
> shipTypeMap[0]->b = 2;
> shipTypeMap[0]->c = 3;
> }
>
> int main(int argc, char* argv[])
> {
> printf("Callback function test.\n");
>
> GameLoader * gl = new GameLoader();
>
> gl->LoadGame();
>
> std::cout<<shipTypeMap[0]->a<<std::endl;//<-----0xC000000005 Access
> Violation here
>
> delete shipTypeMap[0];
>
> getchar();
>
> return 0;
> }
>
The code below compiles and runs as expected.
#include <map>
#include <iostream>
typedef struct _ShipType {
int a;
int b;
int c;
} ShipType;
static std::map<int, ShipType *> shipTypeMap;
struct GameLoader
{
void LoadGame();
};
void GameLoader::LoadGame()
{
shipTypeMap[0] = new ShipType();
shipTypeMap[0]->a = 1;
shipTypeMap[0]->b = 2;
shipTypeMap[0]->c = 3;
}
int main(int argc, char* argv[])
{
printf("Callback function test.\n");
GameLoader * gl = new GameLoader();
gl->LoadGame();
std::cout<<shipTypeMap[0]->a<<std::endl;
delete shipTypeMap[0];
getchar();
return 0;
}