簡體   English   中英

訪問 shared_ptr 矢量對象的問題

[英]Problem with accessing shared_ptr vector objects

我從 main 訪問 shared_ptr Vector 時遇到問題。 我的turnOrder function 采用 2 個 sharedPtr 向量,將它們組合和排序並將對象放入另一個向量( Units )。問題是,當我使用 for 循環測試 function 時,它給出了我想要的,但在 int main(), Units矢量似乎是空的,當我嘗試訪問任何 object 時,它會給出這個退出代碼:“退出代碼 -1073741819 (0xC0000005)”。

void turnOrder( std::vector<std::shared_ptr<Monster>> monsters, std::vector<std::shared_ptr<Hero>> heroes,  std::vector<std::shared_ptr<Unit>> Units) {

    std::vector<std::shared_ptr<Unit>> units;

    units.reserve(8);

    units.insert(units.begin(), heroes.begin(), heroes.end());
    units.insert(units.end(), monsters.begin(), monsters.end());
//TESTING INITIAL VECTOR

    for(int i = 0; i < units.size(); i++){
        units[i]->printOut();
    }
    for (int i = 0; i < units.size(); i++) {
        units[i]->findSpeedRate();
    }
    struct X{

        inline bool operator() ( const std::shared_ptr<Unit> obj1, const std::shared_ptr<Unit> obj2){
            return(obj1->speedRate > obj2->speedRate);
        }
    };
    std::sort(units.begin(), units.end(), X());

    for(int i = 0; i < units.size(); i++){
        Units.emplace_back(units[i]);
    }

//TESTING ORDERED VECTOR
    for(int i = 0; i < Units.size(); i++){
        Units[i]->printOut();
    }

}


int main(){

    std::vector<std::shared_ptr<Unit>> Units;
    std::vector<std::shared_ptr<Monster>> monsters;
    std::vector<std::shared_ptr<Hero>> heroes;

    auto crusader1 = std::make_shared<Crusader>(1);
    heroes.emplace_back(crusader1);
//It goes the same with the other objects(monsters and heroes)

    turnOrder(monsters, heroes, Units);
    Units[0]->printOut();


}

通過引用而不是值傳遞向量。 您正在修改turnOrder內的向量副本 只需將聲明更改為

void turnOrder( std::vector<std::shared_ptr<Monster>>& monsters, std::vector<std::shared_ptr<Hero>>& heroes,  std::vector<std::shared_ptr<Unit>>& Units) {...}

每個變量的區別是& 另外,請參閱此問題以獲取更多信息。

另一張海報有一個關於副本的觀點,但我會看看這個並說如果你要在這個 function 中填充單位,為什么不只返回單位並刪除單位參數。 然后

Units=turnOrder(monsters, heroes)

很有意義。

暫無
暫無

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

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