I have a function myfun
which will return a vector.
vector<double> myfun(const size_t k, const size_t i){
vector<double> v(k);
// do some computation with remaining arguments
return v;
}
Then, I will use it in the loop to update v
and use v
to get some result.
int main(){
size_t N = 100; // iteration size
size_t n = 10; // size of v
vector<double> result(N);
vector<double> v(n);
for(size_t i = 0; i<N; i++){
v = myfun(n,i); // compute for each iteration
result[i] = compute_some_value(v);
}
}
So, my question is:
- Does
v
actually allocated inside ofmyfun
every time it is called? - If it does, what happens to old
v
? - Also, is it better to use just use address like
void myfun(some_args, vector<double> &v)
for output argumentv
?
Yes
When v gets out of scope the destructor is called and the object gets destruct. This is why you don't really have to call destructor of a class explicitly.
It really depends on your use case. If it concerns with memory issues, its better to pass the reference.