交换不使用函数作为参数

时间:2017-08-17 06:14:10

标签: c++ vector stl allocator

#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&lt; int,std :: allocator&lt; int&gt;的匹配函数&gt; :: swap(std :: vector&lt; int,std :: allocator&lt; int&gt;&gt;)'
  /usr/include/c++/4.4/bits/stl_vector.h:929:注意:候选人是:void std :: vector&lt; _Tp,_Alloc&gt; :: swap(std :: vector&lt; _Tp,_Alloc&gt;&amp;)[with _Tp = int,_Alloc = std :: allocator&lt; int&gt;]

但是,当写成func().swap(b)时,它会编译。

它们之间究竟有什么区别?

1 个答案:

答案 0 :(得分:6)

func()返回一个临时对象(右值)。

std::vector::swap()将非const vector&引用作为输入:

void swap( vector& other );

临时对象不能绑定到非const引用(它可以绑定到const引用)。这就是b.swap(func());无法编译的原因。

可以在临时对象超出范围之前调用方法,并且可以将命名变量(左值)绑定到非const引用。这就是func().swap(b)编译的原因。

相关问题