簡體   English   中英

將 std::vector 傳遞給 C++ 中的 function 時的 Memory 分配

[英]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分配 memory 才能使用它(例如,通過調用output->resize(10000) ?)。 因此,我希望在 for 循環中調用func后使用vec時會出現 memory 錯誤,但似乎代碼工作得很好。

你能解釋一下這種行為嗎? 另外,這是您編寫此代碼的方式嗎(即,當您需要一個應該填充向量的 function 時,可能每次都使用不同數量的值,盡管這里是10000 )? (PS。我不想使用return )。

謝謝!

來自std::vector參考

向量的存儲是自動處理的,可以根據需要進行擴展和收縮。

正是std::vector的這種品質使它非常易於使用。

在您的代碼中

*output = temp;

此行將temp向量復制到output中,即調用 賦值運算符 您不必關心這是如何在內部完成的,但您可以假設output指向的向量包含temp的副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM