Does return statement copy values

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

    The returned class or struct may or may not be copied, depending if the compiler uses copy elision. See the answers to What are copy elision and return value optimization? In short, whether it is copied or not depends on a number of things.

    You can of course avoid a copy by returning a reference. In the case of your example, returning a reference is invalid (though the compiler will allow it) because the local struct is allocated on the stack, and therefor the returned reference refers to a deallocated object. However, if the object was passed to your function (directly or as a member of an object) you can safely return a reference to it and avoid copy-on-return.

    Finally, if you cannot trust copy elision and you want to avoid copies, you can use and return a unique_ptr instead of a reference. The object itself will not be copied, although the unique_ptr itself may or may not be (again, depending on copy elision!). Copying/moving a unique_ptr is however very cheap if copy elision of the unique_ptr does not happen for some reason.

    Here is an example using unique_ptr:

    #include 
    
    struct A {
    public:
      int x;
      int y;
    
      A(int x, int y) : x(x), y(y) {
      }
    };
    
    std::unique_ptr returnsA() {
      return std::make_unique(3, 4);
    }
    
    int main() {
      auto a = returnsA();
    }
    

    Note that you must (unfortunately) declare a constructor for your struct, or else make_unique will not compile due to inadequacies of C++.

提交回复
热议问题