[英]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
)。
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.