简体   繁体   English

C ++指针运行时错误-使用指针设置变量然后检索

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

I'm setting up a prototype c++ console application. 我正在设置一个原型c ++控制台应用程序。 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() Actor.cpp // get_Inventory()

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

Inventory.cpp 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. 第一条语句将this->actorInventory复制到局部变量中(例如,在方法get_Inventory的局部变量中),然后返回指向该局部变量的指针。 Once you return from get_Inventory() , that variable goes out of scope and no longer exists. get_Inventory()返回后,该变量将超出范围,并且不再存在。

You may want to try returning a pointer to this->actorInventory directly: 您可能想要尝试直接返回指向this->actorInventory的指针:

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

Or, if you don't want the caller modifying actorInventory , return a const qualified pointer: 或者,如果您不希望调用者修改actorInventory ,则返回一个const限定指针:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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