2017-08-17 53 views
1
#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)书面,它编译。

它们之间的区别究竟是什么?

+0

您的函数返回一个_rvalue_,所以第一个版本无法工作。 – user0042

+0

我认为这是一个有效的问题 - 为什么downvote? – displayname

回答

5

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

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

void swap( vector& other ); 

一个临时对象不能被结合到非const引用(它可以以一个const参考)。这就是为什么b.swap(func());不能编译。

可以在临时对象超出作用域之前调用方法,并且可以将命名变量(左值)绑定到非常量引用。这就是为什么func().swap(b)编译。