Erik Brendel
Erik Brendel

Reputation: 714

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

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.

Upvotes: 1

Views: 473

Answers (1)

Roddy
Roddy

Reputation: 68074

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

Upvotes: 5

Related Questions