Does return statement copy values

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

    Returing objects in C++ done by value and not by reference.

    the reference to subline_t t goes out of scope

    No, the object is copyed.

    will the return statement always copy

    Yes and not... Semantically it behaves like copy, but there is something that is called return value optimization that saves copy constructor.

    foo make_foo()
    {
        foo f(1,2,3);
        return f;
    }
    
    foo ff=make_foo(); /// ff created as if it was created with ff(1,2,3) -- RVO
    foo ff2;
    ff2=make_foo(); /// instance of foo created and then copied to ff2 and then old
                    /// instance destroyed
    

提交回复
热议问题