Does this copy the vector?

↘锁芯ラ 提交于 2020-01-11 06:19:28

问题


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

std::vector<int> x = y.getTheVector();

or would it depend on whether the return type of getTheVector() is by reference?

or would I just need to use:

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

or, would I need to do both?


回答1:


std::vector<int> x = y.getTheVector();

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

std::vector<int>& 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.




回答2:


std::vector<int> x = y.getTheVector();

This is copy-initialization. There are three possible scenarios:

  1. The return value of getTheVector() is a lvalue reference. In this case, the copy constructor is always invoked.
  2. The return value of getTheVector() is a temporary. In this case, the move constructor may be called, or the move/copy may be completely elided by the compiler.
  3. The return value is a rvalue reference (usually a terrible idea). In this case, the move constructor is called.

For this line,

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

This only compiles if getTheVector returns a lvalue reference; a temporary cannot be bound a non-const lvalue reference. In this case, no copy is ever made; but the lifetime problem may be tricky.




回答3:


std::vector<int> x = y.getTheVector();

Your first example does indeed copy the vector, regardless of whether the "getTheVector" function returns a vector or a reference to a vector.

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

In your second example, however, you are creating a reference, so the vector will NOT be copied.



来源:https://stackoverflow.com/questions/23819358/does-this-copy-the-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!