交换不使用函数作为参数

rah*_*yr3 2 c++ stl vector 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;
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,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),它会编译.

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

Rem*_*eau 6

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

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

void swap( vector& other );
Run Code Online (Sandbox Code Playgroud)

临时对象不能绑定到非const引用(它可以绑定到const引用).这就是为什么b.swap(func());不编译.

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