簡體   English   中英

C ++錯誤的分配錯誤

[英]C++ bad alloc error

在我的項目中,有一個可以布置房間的水平班

class Level
{
public:
    Room * exit;
    Room * position;
    Level(Room setExit, Room newPosition);
    ~Level();
    void showPosition();
};

.h文件中具有實現性

Level::Level(Room setExit, Room setPosition)
{
    exit = &setExit;
    position = &setPosition;
}
void Level::showPosition(){
    position->printInfo();
}

房間等級。

class Room
{
    string title;
    string info;
    Room(string titleInput, string infoInput) :info(infoInput), title(titleInput){};
    void printInfo();

.h函數printinfo

void Room::printInfo(){
    cout << title << endl;
}

我運行的主程序。

Room room1("Dungeon", "This is a dangerous room.");
room1.printInfo();
Level lvl1(room1, room1);

這工作正常,但當我打電話時。

lvl1.showPosition();

我得到一個錯誤的分配。 所以我知道錯誤在級別功能showPosition中。 但是,為什么會出現bad_alloc錯誤?

Level構造函數遲早會導致您出現未定義的行為

Level::Level(Room setExit, Room setPosition)
{
    exit = &setExit;
    position = &setPosition;
}

參數setExitsetPosition就像普通的局部變量一樣,換句話說,一旦函數返回,它們將超出范圍(並被破壞)。 剩下兩個散亂的指針,指向現在被破壞的對象(和可重用的內存)。 使用這些指針將為您提供UB。

如果需要使用指針,請將指針作為參數傳遞,並確保它們指向的對象的生存期與Level對象相同(或更長)。

潛在地,您可以在此處使用std::shared_ptr

Level::Level(Room setExit, Room setPosition)
{
    exit = &setExit;
    position = &setPosition;
}

Room是按價值傳遞的。 您存儲將超出范圍的臨時地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM