We have:
vector<int> f(int);
vector<int> v;
This works:
f(x).swap(v);
This doesn't:
v.swap(f(x));
And why?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With