【问题标题】:Problem with accessing shared_ptr vector objects访问 shared_ptr 矢量对象的问题
【发布时间】:2020-08-25 03:36:30
【问题描述】:

我在从 main 访问 shared_ptr Vector 时遇到问题。 我的turnOrder 函数采用 2 个 sharedPtr 向量,将它们组合和排序并将对象放入另一个向量(Units)。问题是,当我使用 for 循环测试函数时,它给出了我想要的 但在 int main() 中,Units 向量似乎为空,当我尝试访问任何对象时,它会给出此退出代码:“退出代码 -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();


}

【问题讨论】:

    标签: c++ vector shared-ptr


    【解决方案1】:

    通过引用而不是值传递向量。您正在修改turnOrder 内的向量的副本。只需将声明更改为

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

    每个变量的区别是&amp;。另外,请参考this question 了解更多信息。

    【讨论】:

      【解决方案2】:

      另一位发帖人有关于副本的观点,但我会看看这个并说如果你要在这个函数中填充单位,为什么不只返回单位并删除单位参数。那么

      Units=turnOrder(monsters, heroes)
      

      很有道理。

      【讨论】:

        猜你喜欢
        • 2015-09-06
        • 1970-01-01
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多