Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is f(x).swap(v) okay but v.swap(f(x)) is not?

Tags:

c++

We have:

vector<int> f(int);

vector<int> v;

This works:

f(x).swap(v);

This doesn't:

v.swap(f(x));

And why?

like image 532
yoyo Avatar asked Nov 05 '10 05:11

yoyo


Video Answer


2 Answers

swap() takes a non-const reference to a vector<int>. A non-const reference cannot bind to an rvalue (a temporary object). A call to a function that returns by value (like f) is an rvalue.

The reason that f(x).swap(v) works is because inside of std::vector<int>::swap, the temporary object returned by f(x) can use this to refer to itself. this is not an rvalue.

like image 50
James McNellis Avatar answered Nov 07 '22 05:11

James McNellis


You are allowed to call member functions on temporaries but in C++ they cannot be bound to non-const references.

For example:

int &x = 5; // illegal because temporary int(5) cannot be bound to non-const reference x
like image 39
Prasoon Saurav Avatar answered Nov 07 '22 05:11

Prasoon Saurav