C++ std::vector::size() 改变它的状态 [英] C++ std::vector::size() changes its state
问题描述
我对 C++ 比较陌生,对一些奇怪的行为感到困惑.我得到一个包含 std::vector 的对象.然后,我用完全相同的复制行打印出它的大小两次:
I'm relatively new to c++ and am confused by some strange behavior. I get an object which contains an std::vector. Then, I print out its size twice, by exactly the same copied line:
Pose& pose = getCurrentPose();
std::cout << "nr1: " << pose.transforms.size() << " bones." << std::endl;
std::cout << "nr2: " << pose.transforms.size() << " bones." << std::endl;
结果:
Nr1: 17 bones.
Nr2: 38294074 bones.
对此向量大小的任何进一步调用都会返回相同的巨大数字(17 应该是正确的).
Any further calls to this vector's size returns the same huge number (17 should be right).
我在迭代向量时也会出错.在我看来,它实际上并未调整大小,但某种端点已损坏.这里发生了什么,我该如何解决这个问题?
I also get errors when iterating over the vector. It seems to me that it hasn't actually resized, but that some kind of end-pointer got corrupted. What is happening here and how can I solve this problem?
getCurrentPose 大致如下所示:
Here is what getCurrentPose roughly looked like:
Pose& getCurrentPose() {
Pose& accu;
for (int b = 0; b < p.transforms.size(); b++) {
BoneState bs;
accu->transforms.push_back(bs);
}
for (int b = 0; b < p.transforms.size(); b++) {
accu->transforms.at(b).loc += getLoc(b);
accu->transforms.at(b).rot += getRot(b);
accu->transforms.at(b).scale += getScale(b);
}
return accu;
}
据我所知,我也不是多线程的.这是一个可能相关的 OpenGL 应用程序.
I am also not multi-threading anywhere as far as I know. This is an OpenGL-application, which may be related.
推荐答案
我敢打赌 GetCurrentPose()
看起来很危险.
My bet is that GetCurrentPose()
looks dangerously like this.
Pose & GetCurrentPose()
{
Pose p;
p = something_magic();
return p;
}
或者,按照您自己的回答...
or, following your own answer...
Pose * GetCurrentPose()
{
Pose p;
p = something_magic();
return &p;
}
两者都是导致混乱的万无一失的方法,返回对已离开作用域的对象的指针和引用.
Both are a surefire recipe for chaos, returning pointers and references to objects which have left scope.
正确的方法通常是按值返回.如果 Pose
对象由于某种原因不可复制,则您需要非常仔细地考虑整个设计.
The right approach for this is typically return-by-value. If Pose
objects aren't copyable for some reason, you need to think through your whole design very carefully.
Pose GetCurrentPose()
{
Pose p;
p = something_magic();
return p; // theoretically this returns a copy of p, but the compiler can optimise out the copying step.
}
这篇关于C++ std::vector::size() 改变它的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!