Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does return statement copy values

Tags:

c++

return

I am wondering about this because of scope issues. For example, consider the code

typedef struct {     int x1;/*top*/     int x2;/*bottom*/     int id; } subline_t;    subline_t subline(int x1, int x2, int id) {     subline_t t = { x1, x2, id };     return t; }  int main(){     subline_t line = subline(0,0,0); //is line garbage or isn't it? the reference     //to subline_t t goes out of scope, so the only way this wouldn't be garbage     //is if return copies } 

So my question is, will the return statement always copy? In this case it seems to work, so I am led to believe that return does copy. If it does copy, will it copy in every case?

like image 200
ldog Avatar asked Oct 07 '09 04:10

ldog


People also ask

Are return values copied?

If a function returns a reference, and that reference is used to initialize or assign to a non-reference variable, the return value will be copied (as if it had been returned by value).

What does a return statement do?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

What statement is used to return a value?

The 'return statement' is used to return a value in a function.


1 Answers

Yes, in that case there will be a copy made. If you change the function declaration like this:

subline_t &subline(int x1, int x2, int id) { 

then no copy will be made. However, in your specific case it would not be valid to return a reference to an object allocated on the stack. The problem is that the object would be destructed and invalidated before the caller had a chance to use it.

This is related to the common Return Value Optimization for C++ that can avoid doing an actual copy operation in the case you have described. The end result is (or should be) the same as if a copy were done, but you should be aware of the optimization. The presence of this optimization can, in some cases, change the observable behaviour of the program.

like image 87
Greg Hewgill Avatar answered Oct 15 '22 15:10

Greg Hewgill