Search code examples
c++arraysvectorstlpush-back

STL push_back: previous values getting modified when pushing a dynamically changing array


I am having a very strange problem with std::vector.push_back() in my CPP code. Basically, all I am doing is:

void func()
{
  if(first_time_coming_here)
  {
    do_some_stuff();
    V.push_back(Mat::zeros(3,1,CV_32FC1));  // OpenCV Mat structure
    V.push_back(Mat_array_that_gets_updated_in_another_function);
  }
  else
  {
    do_other_kinds_of_stuff();
    V.push_back(Mat_array_that_gets_updated_in_another_function);   
  }
}

Let's say the array that gets updated in the previous function is [1,1,1] initially and then the second time I execute func(), it has already become [2,2,2]. My output then should be

V = [ [0,0,0], [1,1,1], [2,2,2] ]

But instead, it is

V = [ [0,0,0], [2,2,2], [2,2,2] ]

I am really stumped as to what's going on here. The only thing that would make sense is if V is storing the CURRENT value of the array instead of what has already been passed: but once push_back() is called, shouldn't the element take the value and keep it in memory no matter what happens to the variable that is bringing the value in? V is defined as a vector of cv::Mat.

EDIT: This has been solved by clearing the value of the array between both the function calls, like:
array = Mat::zeros(1,1,CV_32FC1);
Yet, I wonder why using it directly does not work.


Solution

  • You did a dangerous thing, you pushed a copy of an object without respecting the pointers inside that object or the memory to which they point. The object you pushed has memberwise assigned data members from the original, so as soon as the original object goes away, your program will crash.

    The solution is to push a clone of the object instead:

    V.push_back(Mat_array_that_gets_updated_in_another_function.clone ());