Does this copy the vector?

前端 未结 3 1984
夕颜
夕颜 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();
    

    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& 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.

提交回复
热议问题