3
votes
#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?

1
Your function returns a rvalue, so the 1st version cannot work.user0042
I think this is a valid question - why downvote?Stefan Falk

1 Answers

6
votes

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.