【发布时间】:2018-01-25 10:29:17
【问题描述】:
#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()) 没有编译。它给出了一个错误:
没有匹配函数调用‘std::vector
>::swap(std::vector >)’
/usr/include/c++/4.4/bits/stl_vector.h:929:注意:候选者是:void std::vector<_tp _alloc>::swap(std::vector<_tp _alloc>&) [with _Tp = int, _Alloc = std::allocator]
但是,当写成 func().swap(b) 时,它会编译。
它们之间到底有什么区别?
【问题讨论】:
-
你的函数返回一个rvalue,所以第一个版本不能工作。
-
我认为这是一个有效的问题 - 为什么要投反对票?