简体   繁体   中英

C++ Error: no matching function for call to 'std::vector<int>::swap(std::vector<int>)'

I was reading a blog about std::vector. See the Swapping contents section in this website .


Basically, it says a common application of swap() method is forcing a vector to release the memory it holds. But after I ran the code below, I got the error Error: no matching function for call to 'std::vector<int>::swap(std::vector<int>)'| . Where has gone wrong?


#include <iostream>
#include <vector>

int main( )
{
    std::vector<int> v;
    v.push_back(1); v.push_back(2);
    v.clear();
    v.swap(std::vector<int>(v));
    return 0;
}

The parameter type of std::vector::swap is a non-const lvalue reference (ie vector& ). But std::vector<int>(v) is a temporary object, which can't be bound to non-const reference.

That means when use "swap trick", you should put the temporary on the left side:

std::vector<int>(v).swap(v);

Since C++11 you could use std::vector::shrink_to_fit for requesting the removal of unused capacity; note this is a non-binding request, the effect depends on implementation.

std::vector::swap() does not accept a temporary object as input. It takes the input object as a non-const lvalue reference (so it can modify the input object). A non-const lvalue reference cannot bind to a temporary object (only a const lvalue reference or an rvalue reference can do that), which is why you get the compiler error.

You should also use the default constructor and not the copy constructor, to ensure that the original vector gets swapped with an empty state, and the temporary vector assumes ownership of the original allocated memory.

Using your original code, you would need to declare another vector variable to swap with:

std::vector<int> temp;
v.swap(temp);

Otherwise, switch the order of the two objects around, which is the preferred approach:

std::vector<int>().swap(v);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM