#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 <int,std :: allocator <int >>> :: swap(std :: vector <int,std :: allocator <int >>)'/ 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 ::分配器<int>的]
但是,当写成 func().swap(b)
时,它会编译 .
他们之间究竟有什么区别?
1 回答
func()
返回临时对象(右值) .std::vector::swap()将非const
vector&
引用作为输入:临时对象不能绑定到非const引用(它可以绑定到const引用) . 这就是
b.swap(func());
无法编译的原因 .可以在临时对象超出范围之前调用方法,并且可以将命名变量(左值)绑定到非const引用 . 这就是
func().swap(b)
汇编的原因 .