#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;
}
在上面的代碼中,b.swap(func())
未編譯。它給出了一個錯誤:交換不與功能一起作爲參數
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>]
但是,當作爲func().swap(b)
書面,它編譯。
它們之間的區別究竟是什麼?
您的函數返回一個_rvalue_,所以第一個版本無法工作。 – user0042
我認爲這是一個有效的問題 - 爲什麼downvote? – displayname