Does this copy the vector?

前端 未结 3 2018
夕颜
夕颜 2021-01-14 12:38

If I have the following code, is the vector copied?

std::vector x = y.getTheVector();

or would it depend on whether the return t

3条回答
  •  长情又很酷
    2021-01-14 13:19

    std::vector x = y.getTheVector();
    

    always makes a copy, regardless of the return type of y.getTheVector();.

    std::vector& x = y.getTheVector();
    

    would not make a copy. However, x will be valid as long as y.getTheVector() returns a reference to an object that is going to be valid after the function returns. If y.getTheVector() returns an object created in the function, x will point to an object that is no longer valid after the statement.

提交回复
热议问题