Ameer Jewdaki
Ameer Jewdaki

Reputation: 1798

c++ passing big vectors as output

I have several big vector (roughly with a million elements), lets say vector<int> v generated in a function or a class member function. I want to use this vector outside of this function/member efficiently, i.e., avoid copying it entirely when I pass it as an output

vector<int> make_vect() {
    vector<int> v(1e6); 
    ...      // some analysis
    return v;
}

int main() {
vector<int> v = make_vect();
}

I know that I can use a pointer to this vector vector<int> *v instead, but that would complicate things a little bit (for instance I have to delete them manually and so on). I was wondering how the code above behaves if I don't use a reference or pointer.

Apart from copying issue, in the code above when is the allocated memory freed? Is the content never deleted unless I call v.clear()? or it automatically deletes them when there's no variable pointing to the container left?

Upvotes: 1

Views: 124

Answers (3)

Alexx Murphy
Alexx Murphy

Reputation: 55

Though both passing by value and using pointers would work in this specific instance, I wouldn't discount using pointers because they're a little more complicated. If you're doing any dynamic allocation, it might actually simplify your process to start with pointers now so you don't have to go back and change everything later. Just my two cents!

Upvotes: 0

Matt Timmermans
Matt Timmermans

Reputation: 59174

I like to do it like this:

void make_vect(vector<int> *dest)
{
    dest->resize(1000000); 
    ...      // some analysis
}

int main()
{
    vector<int> v;
    make_vect(&v);
}

Others would use a vector & instead of a vector *, but I think using the pointer indicates that the called function is expected to write into it.

Upvotes: 0

Blindy
Blindy

Reputation: 67380

That's exactly how you're supposed to return objects -- by value. The compiler will apply NRVO optimizations to ensure no copying takes place.

Upvotes: 4

Related Questions