Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending back a vector from a function

How to translate properly the following Java code to C++?

Vector v;
v = getLargeVector();
...
Vector getLargeVector() {
    Vector v2 = new Vector();
    // fill v2
    return v2;
}

So here v is a reference. The function creates a new Vector object and returns a reference to it. Nice and clean.

However, let's see the following C++ mirror-translation:

vector<int> v;
v = getLargeVector();
...
vector<int> getLargeVector() {
    vector<int> v2;
    // fill v2
    return v2;
}

Now v is a vector object, and if I understand correctly, v = getLargeVector() will copy all the elements from the vector returned by the function to v, which can be expensive. Furthermore, v2 is created on the stack and returning it will result in another copy (but as I know modern compilers can optimize it out).

Currently this is what I do:

vector<int> v;
getLargeVector(v);
...
void getLargeVector(vector<int>& vec) {
    // fill vec
}

But I don't find it an elegant solution.

So my question is: what is the best practice to do it (by avoiding unnecessary copy operations)? If possible, I'd like to avoid normal pointers. I've never used smart pointers so far, I don't know if they could help here.

like image 578
Jabba Avatar asked Jul 02 '26 05:07

Jabba


2 Answers

Most C++ compilers implement return value optimization which means you can efficiently return a class from a function without the overhead of copying all the objects.

I would also recommend that you write:

vector<int> v(getLargeVector());

So that you copy construct the object instead of default construct and then operator assign to it.

like image 51
R Samuel Klatchko Avatar answered Jul 04 '26 00:07

R Samuel Klatchko


void getLargeVector(vector<int>& vec) { 
    // fill the vector
} 

Is a better approach for now. With c++0x , the problem with the first approach would go by making use of move operations instead copy operations.

like image 42
Jagannath Avatar answered Jul 04 '26 01:07

Jagannath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!