Search code examples
c++vectorswaptemporary-objects

vector<T>::swap and temporary object


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?


Solution

  • 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.