0

So I have a constructor that takes a vector<num>& and them std::move's this reference. Isn't this objectively better than taking vector<num> if my intention is to move the argument?

In the second case, as I see it, it's guaranteed that no copies will be inadvertently created when they pass the vec to the constructor.

For the first case, maybe the compiler might optimize out the copy with a move, maybe not, or maybe the user will explcitly do foo(std::move(my_vec));, maybe not...in sum, there's no guarantee that it will be moved.

I understand that if I do use a l-value reference, I wouldn't be able to accept temporaries. Is there any other drawback(s) to it?

1 Answer 1

2

You should always prefer pass-by-reference (passing std::vector<int>& or std::vector<int> const&) over pass-by-value (passing just std::vector<int>) because when passing by reference you are avoiding unnecessary copies.

However, you should not use std::move on an l-value reference. std::move is used with move-constructors which receive r-value reference like:

Foo(std::vector<int>&& v) : v_(std::move(v)) {} 
Sign up to request clarification or add additional context in comments.

7 Comments

why is that std::move in there? It seems pointless because v is already a temporary
@nz_21 A named object is never a temporary. Thus v isn’t either. And no, you should in general not use std::move on an lvalue reference since it steals ownership (there are rare cases where it’s OK but these need to be handled with care). You can, however, use it on lvalues (i.e. if you passed the vector by value).
@KonradRudolph thanks for explaining this. I was a bit busy...
@KonradRudolph Apologies for the incorrect semantics, I meant a reference binding to a temporary, not the temporary itself. I don't get why you need to move a reference binding to a temporary.
@nz_21 That’s just how the language is defined. If you have T&& x = some_value; T y = x;, then some_value gets copied into y. You need to use std::move(x) to move the value instead. See godbolt.org/z/vfOVPA
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.