【问题标题】:std::vector not retaining data?std::vector 不保留数据?
【发布时间】:2011-02-09 21:10:42
【问题描述】:

我有这个代码:


void BaseOBJ::update(BaseOBJ* surround[3][3])
{
    forces[0]->Apply(); //in place of for loop
    cout << forces[0]->GetStrength() << endl; //forces is an std::vector of Force*
}

void BaseOBJ::AddForce(float str, int newdir, int lifet, float lifelength) {

Force newforce;
newforce.Init(draw, str, newdir, lifet, lifelength);
forces.insert(forces.end(), &newforce);
cout << forces[0]->GetStrength();

}

现在,当我调用 AddForce 并产生一个强度为 1 的无限力时,它 cout 为 1。但是当调用 update 时,它​​只输出 0,就好像该力不再存在一样。

【问题讨论】:

    标签: c++ vector std


    【解决方案1】:

    您在向量中存储了指向 force 的指针,但 force 是函数本地的。

    您必须使用new 在堆中创建。

    Force* f = new Force;
    forces.push_back(f);
    

    【讨论】:

    【解决方案2】:

    你需要用 new 创建你的 Force:

    Force *newforce = new Force;
    newforce->Init(draw, str, newdir, lifet, lifelength);
    forces.insert(forces.end(), newforce); // or: forces.push_back(force);
    

    您的代码发生的情况是您的对象保留在堆栈中,在您离开函数并执行其他操作后,它会被覆盖。

    为什么是指针向量?可能您需要 Force 的向量,而不是 Force*。您还必须在扔掉向量之前删除它的所有元素!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 2018-10-23
      • 2017-05-27
      • 1970-01-01
      • 2012-12-13
      • 2012-10-19
      相关资源
      最近更新 更多