将 std::vector 传递给 C++ 中的函数时的内存分配

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

考虑以下简单示例:

#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;
}

我曾经认为必须先为 vec 分配内存才能使用它(例如,通过调用 output->resize(10000)?)。因此,我预计在 for 循环中调用 func 后使用 vec 时会出现内存错误,但似乎代码工作正常。

你能解释一下这种行为吗?另外,这是您编写此代码的方式吗(即,当您需要一个应该填充向量的函数时,也许每次都使用不同数量的值,尽管这里是 10000)? (PS。我不想使用 return)。

谢谢!

来自 reference for std::vector:

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

正是 std::vector 的这种品质使其非常易于使用。

在你的代码中

*output = temp;

此行将 temp 向量复制到 output,即调用 assignment operator。您不必关心这是如何在内部完成的,但您可以假设 output 指向的向量包含 temp.

的副本