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();
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With