[英]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. 现在,当我调用AddForce并以1的强度进行无穷大作用时,其cout为1。但是在调用update时,它仅输出0,就好像该作用力不再存在。
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. 您必须使用
new
在堆上创建。
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*.
可能您想要的是Force的向量,而不是Force *。 You would also have to delete all elements of your vector before you throw it away!
您还必须删除向量中的所有元素,然后再将其丢弃!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.