Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 528
Alcott Avatar asked Jan 15 '12 03:01

Alcott


People also ask

Does STD swap work on vectors?

The std::vector::swap function will always swap the contents of vector in constant time. In practice, both the functions will swap the contents of vectors in O(1) time and give the same performance.

What does std :: swap do?

The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables. Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type.

What is std vector in c++?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

When to use vector in c++?

In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library.


1 Answers

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.

like image 52
Oliver Charlesworth Avatar answered Oct 21 '22 08:10

Oliver Charlesworth