开发者

std::vector not retaining data?

I have this code:


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();

}

Now, when I call AddForce and make an infinite force with a strength of one, it cout's 1. But when update is called, it just outputs 0, as if the force were no longer there.


You are storing a pointer to force in your vector but the force is function local.

You must use new to create in on the heap.

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


You need to create your Force with new:

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

What happens with your code is that your object remains on the stack, after you leave the function and do something else, it gets overwritten.

Why a vector of pointers? Probably you want a vector of Force, not Force*. You would also have to delete all elements of your vector before you throw it away!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜