c++rvalue-referencepass-by-rvalue-reference

Pass input parameters as rvalue references?


Is it a good idea to pass parameters as rvalue references just to make it clear that you're going to manipulate the argument? Kinda like the opposite of const correctness.

For example, this function that takes a vector of strings, manipulates it somehow and returns a boolean value:

static bool isThisSomething(std::vector<string>&& input1);

Now if the caller wants to call this function with an lvalue, he has to use std::move() and acknowledge that this vector will be messed with. This should prevent unexpected side effects.

std::vector<std::string> lvalueVector = {"foo", "bar"};
bool somethingness = isThisSomething(std::move(lvalueVector)); 

Clarification:
The manipulations that isThisSomething does, are just part of some internal logic and would appear like nonsense for the caller.


Solution

  • Is it a good idea to pass parameters as rvalue references just to make it clear that you're going to manipulate the argument?

    Not in general. In particular, it depends on how you are manipulating the argument.

    If you accept a parameter by rvalue, then you are implying that the argument will be left in an unspecified, typically moved-from state. If that is what the function does, then rvalue reference is indeed appropriate. Note that depending on use case, passing the argument by value is often a good alternative in this case.

    That is the opposite implication that you would want to make when you modify the object such that the caller might find the modified state useful. Lvalue reference to non-const implies that the argument will be manipulated in this way.