2017-08-17 76 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)編譯。