Does return statement copy values

前端 未结 11 1816
夕颜
夕颜 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:20

    It returns a copy, which is what you want it to do. Changing it to return a reference will result in undefined behaviour in the assignment to line.

    However, the idiomatic way to do this in C++ is with constructors and assignment lists. This encapsulates code and data structures better, and allows you to avoid the plethora of intermediate objects that compilers are free to construct/destruct/copy.

    struct subline_t {
            int x1;/*top*/
            int x2;/*bottom*/
            int id;
    
    // constructor which initialises values with assignment list.
      subline_t(int the_x1, int the_x2, int the_id) :
        x1(the_x1),
        x2(the_x2),
        id(the_id)
      {
      }
    };
    
    
    int main(){
        subline_t line2(0,0,0); // never requires a copy or assignment.
    }
    

提交回复
热议问题