Search code examples
c++memoryvector

C++ vector initialization: what is actually going on using this syntax?


I saw a bit of code on another site and I am wondering about the subtleties of what is going on.

Consider a function that initializes a vector

vector<float>  initvec  ( int nx,  int ny,  int nz ) {
  vector<float> data;
  for (int i = 0; i < nx * ny *nz; ++i){ // assign data elements with sequential values from 0 to nx*ny*nz-1}
  return data;
}

then later

void other( int nx, in ny, int nz ) {
  …
  vector<float> A( initvec  ( nx, ny, nz ) );
  …
}

I am not clear as to what is literally going on when the vector “A” is created. It seems at least like an unnecessary duplication of memory.


Solution

  • I think that you wonder why doesn't we simply assign the results of the initvec function to the A variable instead of calling a constructor.

    In fact, it doesn't matter in C++. You think, that there is an unnecessary copy going on but it is not the case. Since vector is actually a class the behaviour in languages like C# or Java would be to simply copy the returned reference when assigning to the A variable.

    In C++ we have the move semantics - it means that the memory would be reused in this scenario. In initvec, data was allocated on the stack and then copied along the return statement. Then this memory was reused by the move constructor of vector class.

    Another thing, we couldn't return the reference of data since it is allocated on the stack (avoiding allocating memory on return). Once we leave the function address to the local variable is no longer valid. We could however allocate this vector on the heap with the new operator or using smart pointers and return it. This would imitate the behavior of the languages that I mentioned earlier. Remember, that in the former case you trust a user of initvec function to free the allocated memory.