简体   繁体   中英

C++ pointers runtime error - setting a variable with pointers then retrieving

I'm setting up a prototype c++ console application. The program contains some virtual classes and pointers etc. When the program reaches the lines of code below in the main function it crashes. I believe it is something to do with accessing the memory at that pointer.

main()

...
Player _player();  //new player object created
Actor *player = &_player;  //pointer to player created

...
//note player and get_inventory() are/return a pointer
{
 Inventory* a =  player->get_Inventory();
 a->set_testMe("testedMe");
 string result = a->get_testMe();
 cout << result << endl;
}

{
 Inventory* a =  player->get_Inventory();
 string result = a->get_testMe();  //This causes error
 cout << result << endl;
}
...

Actor.cpp //get_Inventory()

...
Inventory* Actor::get_Inventory()
{
    Inventory mInventory = this->actorInventory;
    Inventory * pInventory = &mInventory;
    return pInventory;
}
...

Inventory.cpp

...
Inventory::Inventory()
{
this->testMe = "initial test";
}

void Inventory::set_testMe(string input)
{
    this->testMe = input;
}
string Inventory::get_testMe()
{
    return this->testMe;
}
...

Any ideas? Thanks

This returns a pointer to a local variable:

Inventory* Actor::get_Inventory()
{ 
    Inventory mInventory = this->actorInventory;
    Inventory * pInventory = &mInventory;
    return pInventory;
}

The first statement copies this->actorInventory into a local variable (as in, local to the method get_Inventory ), and then returns a pointer to that local variable. Once you return from get_Inventory() , that variable goes out of scope and no longer exists.

You may want to try returning a pointer to this->actorInventory directly:

Inventory *Actor::get_Inventory()
{
    return &actorInventory;
}

Or, if you don't want the caller modifying actorInventory , return a const qualified pointer:

const Inventory *Actor::get_Inventory() const
{
    return &actorInventory;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM