C++ std::vector::size() changes its state

一曲冷凌霜 提交于 2019-12-12 00:02:40

问题


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;

The result:

Nr1: 17 bones.
Nr2: 38294074 bones.

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?

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;
}

I am also not multi-threading anywhere as far as I know. This is an OpenGL-application, which may be related.


回答1:


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.

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.
}


来源:https://stackoverflow.com/questions/37730549/c-stdvectorsize-changes-its-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!