Pass by Reference an vector inline

Viewed 263

i'm trying to pass an vector by reference, which gets modified inside the function (lets say, something like sorting the vector)

void dummy(vector<int> &v) { sort(v.begin(), v.end()); }

The above works only when creating the vector like this and passing the reference, which is expected.

int main() {
  vector<int> v = {1, 2, 3};
  dummy(v);
}

I'm trying to figure out, if there is an inline way of doing this ? Usually, if the vector is not getting modified we can do something like this -

int main() {
  dummy({1,2,3})
}

But, when the vector gets modified, it throws an compilation error saying - cannot bind non-const lvalue reference of type 'std::vector&' to an rvalue of type 'std::vector. So, is there a way to send the vector's reference inline?

3 Answers

In that case you should write an overload for an rvalue reference, namely:

void dummy(vector<int>&&);

This will work with the temporary object passed to the function.

If the vector is not getting modified, you can use const to reference:

void dummy(const vector<int> &v) { .. }

dummy(vector<int>{1, 2, 3});

You can also use universal references &&:

void dummy(vector<int> &&v) { .. }

To elaborate on masoud's answer, if you are passing an outside vector into a function that accepts is as a universal reference you may need to use std::move to avoid a compiler error or implicit duplication of the object. It's best practice to explicitly use std::move when passing something that is not already an explicit universal reference.

The compiler error is intended to avoid a mistake by the developer (accessing the object after its ownership has moved which may have undefined or unexpected behavior depending on the object type). So std::move implies your intention to forfeit outside ownership of the object in question. And depending on what class you are using, it may duplicate the object before passing it in as a universal reference, so std::move would prevent that unintended possibility as well.

void dummy(vector<int> &&v) { ... }

vector<int> myVector = {1, 2, 3};
dummy(std::move(myVector));
Related