Does return statement copy values

前端 未结 11 1731
夕颜
夕颜 2020-12-23 08:56

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

typedef struct {
    int x1;/*top*/
    int x2;/*bottom*/
    int id;
} sub         


        
11条回答
  •  生来不讨喜
    2020-12-23 09:35

    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.

提交回复
热议问题