#include <bits/stdc++.h>
using namespace std;
vector<int> func()
{
vector<int> a(3,100);
return a;
}
int main()
{
vector<int> b(2,300);
//b.swap(func()); /* why is this not working? */
func().swap(b); /* and why is this working? */
return 0;
}
In the code above, b.swap(func()) is not compiling. It gives an error:
no matching function for call to ‘std::vector<int, std::allocator<int> >::swap(std::vector<int, std::allocator<int> >)’
/usr/include/c++/4.4/bits/stl_vector.h:929: note: candidates are: void std::vector<_Tp, _Alloc>::swap(std::vector<_Tp, _Alloc>&) [with _Tp = int, _Alloc = std::allocator<int>]
But, when written as func().swap(b), it compiles.
What exactly is the difference between them?
func() returns a temporary object (an rvalue).
std::vector::swap() takes a non-const vector& reference as input:
void swap( vector& other );
A temp object cannot be bound to a non-const reference (it can to a const reference). That is why b.swap(func()); does not compile.
Methods can be called on a temp object before it goes out of scope, and a named variable (an lvalue) can be bound to a non-const reference. That is why func().swap(b) compiles.
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