Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning the return of another function

If I want to call Bar() instead of Foo(), does Bar() return me a copy (additional overhead) of what Foo() returns, or it returns the same object which Foo() places on the temporary stack?

vector<int> Foo(){  
    vector<int> result;  
    result.push_back(1);  
    return result;  
}  
vector<int> Bar(){  
    return Foo();  
}
like image 424
blizpasta Avatar asked Oct 03 '08 09:10

blizpasta


2 Answers

Both may happen. However, most compiler will not do copy as soon as you optimize.

Your code indicate there should be a copy. However, the compiler is allowed to remove any copy that do not change the semantic and the program.

Note: This is why you should NEVER have a copy constructor that does anything but copying correctly as you can never be sure if a copy will be actually done or not.

like image 73
PierreBdR Avatar answered Nov 07 '22 17:11

PierreBdR


This is a trivial case for NRVO – names return value optimization (a misnomer in this case since there's no name). Stan Lippman hat a blog entry with a nice explanation of the mechanism involved.

like image 29
Konrad Rudolph Avatar answered Nov 07 '22 17:11

Konrad Rudolph