#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;
}
Dans le code ci-dessus, b.swap(func())
ne compile pas. Il donne une erreur:swap ne fonctionne pas avec la fonction comme paramètre
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>]
Mais, lorsqu'il est écrit comme func().swap(b)
, il compile.
Quelle est exactement la différence entre eux?
Votre fonction renvoie un _rvalue_, donc la 1ère version ne peut pas fonctionner. – user0042
Je pense que c'est une question valide - pourquoi downvote? – displayname