vector<T>::swap and temporary object
-
16-04-2021 - |
Pergunta
Code goes below:
#include <vector>
int main()
{
vector<int> v1(5,1);
v1.swap(vector<int> ()); //try to swap v1 with a temporary vector object
}
The code above cannot compile, error:
error: no matching function for call to ‘std::vector<int, std::allocator<int> >::swap(std::vector<int, std::allocator<int> >)’
But, if I change the code to something like this, it can compile:
int main()
{
vector<int> v1(5,1);
vector<int> ().swap(v1);
}
Why?
Solução
Because vector<int>()
is an rvalue (a temporary, roughly speaking), and you cannot bind a non-const
reference to an rvalue. So in this case, you cannot pass it to a function taking a non-const
reference.
However, it's perfectly fine to invoke member functions on temporaries, which is why your second example compiles.
Outras dicas
The call v1.swap(std::vector<int>())
tries to bind a temporary (i.e. std::vector<int>()
) to a non-const reference. This is illegal and fails. On the other hand, using std::vector<int>().swap(v1)
calls a non-const function on the [non-const] temporary which is allowed.
In C++2011 I would have thought that the declaration would be changed to std::vector<T>::swap(T&&)
and it would thus become OK to use swap()
with temporaries (but, obviously, still not with const
objects). As GMan pointed out this isn't the case.