3

I have a strange problem. There is a vector of structures. With a temporary structure, I push_back to that vector of structures. But when I check the first member's cnt, I see that it became changed. Any idea? (Below code is a simplified version but a representative one)

struct Vector
{
  float *dim;

  Vector ()
  {
    dim = new float [3];
  }
};

struct Face
{
  float an_N, an_P;
  int P, N;
  Vector Af;
  float Ad;
  Vector cnt;
  float ifac;
  float mf;
};

std::vector <Face> face;

Face temp_face;

for (;;)
{
    temp_face.cnt.dim[0] = 0.f;
    temp_face.cnt.dim[1] = 0.f;
    temp_face.cnt.dim[2] = 0.f;

    for (int q=0; q<n_vtx_2D; ++q)
    {
        temp_face.cnt = temp_face.cnt + pt[vtx[q]] / n_vtx_2D;                
    }                 

    face.push_back(temp_face);
}

std::cout << face[0].cnt.dim[0] << std::endl;

Output

0.25

0

Shibli
  • 5,879
  • 13
  • 62
  • 126

1 Answers1

5

The default compiler generated copy constructor (and assignment operator) is being used for Vector and Face (but most importantly Vector). As the code re-uses the same instance of Face, named temp_face, all the instances of Face in the vector face point to the same Face.cnt.dim array (as the faces will contain copies of temp_face).

I can't see any reason for dynamically allocated the array inside Vector as it is a fixed size. Suggest changing to:

struct Vector
{
    float dim[3];
};

Or you need to implement copy constructor, assignment operator and destructor for Vector. See What is The Rule of Three? for more information.

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252