Erwan Daniel
Erwan Daniel

Reputation: 1537

emplace_back modify the value in parameter

I'm writing some code and figured out a problem with emplace_back on vector.

void generateTube(std::vector<glm::vec3> &vertices, const glm::vec3 &pos) {
   glm::vec3 N, B;
   float cos, sin;

   ...

   for (int i = 0 ; i < 2 ; i++) {
      ...
      std::cout << pos << std::endl;
      vertices.emplace_back(pos + cos * N + sin * B);
      std::cout << pos << std::endl;
      ...
   }
}

The result output :

[0.000000, 0.000000, -1.000000]
[-1998397155538108416.000000, -1998397155538108416.000000, -1998397155538108416.000000]

As you can see the value of pos if modified by emplace_back. If I remove the call, the value is never changed.

Do you have an explanation ? I use the vs2019 compilator on Windows 10, arch is x86_amd64.

Upvotes: 0

Views: 367

Answers (1)

Daniel Langr
Daniel Langr

Reputation: 23497

Yes pos refer to an element of vertices...

That's the problem. During emplace_back, reallocation of vector elements may be triggered, which invalidates all iterators/refernces/pointers to vector elements, including pos. Dereferencing pos then causes undefined behavior.

A simple remedy might be to reserve enough vector space before initializing pos parameter, which will make sure that no reallocation happens during function call.

Upvotes: 1

Related Questions