简体   繁体   中英

Memory allocation when passing a std::vector to a function in C++

Consider the following simple example:

#include <vector>

void func(std::vector<int>* output) {
  std::vector<int> temp(10000);
  /* ... do work here and fill temp with useful values ... */

  // now send the result to main
  *output = temp;
}

int main(void) {
  std::vector<int> vec;
  // func will put useful values in vec
  func(&vec);

  for(size_t i=0; i<10000; i++)
    vec[i] = 3; // just checking to see if I get a memory error

  return 0;
}

I used to think one has to first allocate memory for vec before being able to use it (eg, by calling output->resize(10000) ?). Therefore I expected to get a memory error when using vec after calling func in the for loop, but it seems that the code works just fine.

Can you please explain this behavior? Also, is this how you'd write this code (ie, when you need a function that is supposed to fill a vector, perhaps each time with a different number of values although here it's 10000 )? (PS. I don't want to use return ).

Thanks!

From the reference for std::vector :

The storage of the vector is handled automatically, being expanded and contracted as needed.

It is precisely this quality of std::vector that renders it quite easy to use.

In your code

*output = temp;

This line copies the temp vector into output , ie, invoking the assignment operator . You do not have to take care of how this is internally done, but you can assume that after that the vector pointed by output contains a copy of temp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM