#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