Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value optimization: ho can I avoid copy construction of huge STL containers.

Tags:

c++

rvo

When I want a function to return me a container:

vector<T> func(){
    vector<T> result;
    ...
    return result; 
}

To be used in the following way:

vector<T> result = func(); 

In order to avoid the overhead of copying my container I often write the function so that it returns nothing but accept a non-const instance of the container.

void func(vector<T>& result){
    result.clear();
    ...
    result;
}

To be used in the following way:

vector<T> result;
func(result); 

Is my effort meaningless because I can be sure that the compiler always uses the return value optimization?

like image 233
jimifiki Avatar asked Nov 06 '15 08:11

jimifiki


1 Answers

It is meaningless. The type of RVO you mentioned is called named RVO (NRVO), and most compilers implement it.

Regardless, in C++11, vector has move constructors, so even if NRVO didn't apply, it'd still be moved, not copied.

like image 153
Chris Jester-Young Avatar answered Oct 01 '22 23:10

Chris Jester-Young