2015-03-31 45 views
0

我目前正試圖通過這個post瞭解複製和交換習慣用法。發佈的答案具有下面的代碼在它通過臨時作爲參考

class dumb_array 
{ 
public: 
    // ... 

    friend void swap(dumb_array& first, dumb_array& second) // nothrow 
    { 
     // enable ADL (not necessary in our case, but good practice) 
     using std::swap; 

     // by swapping the members of two classes, 
     // the two classes are effectively swapped 
     swap(first.mSize, second.mSize); 
     swap(first.mArray, second.mArray); 
    } 

    // move constructor 
    dumb_array(dumb_array&& other) 
     : dumb_array() // initialize via default constructor, C++11 only 
    { 
     swap(*this, other); //<------Question about this statement 
    } 

    // ... 
}; 

我注意到,作者使用這個聲明

swap(*this, other); 

other是一個臨時的或正在被作爲該方法交換一個引用傳遞一個rvalue。我不確定是否可以通過引用傳遞一個右值。 爲了測試這一點,我試着這樣做但是下面沒有工作,直到我的參數轉換爲const reference

void myfunct(std::string& f) 
{ 
    std::cout << "Hello"; 
} 

int main() 
{ 
    myfunct(std::string("dsdsd")); 
} 

我的問題是如何能夠other被臨時被引用在swap(*this, other);傳遞而myfunct(std::string("dsdsd"));不能是通過參考傳遞。

+1

我認爲你需要了解什麼是右值引用是:http://stackoverflow.com/a/5481588/4342498 – NathanOliver 2015-03-31 19:08:28

+1

swap(* this,other);'是錯誤的。它必須是'swap(* this,std :: move(other));'(其他是一個命名變量) – 2015-03-31 19:12:03

+0

@DieterLücking在這種情況下,交換方法不會工作,因爲它需要一個引用,並且你傳遞一個臨時的。如果它是一個不變的參考,它只會按照你的建議工作。請糾正我,如果我錯了 – Rajeshwar 2015-03-31 19:13:40

回答

7

該構造函數採用右值引用,但other是一個左值(它有一個名稱)。

+0

是的,這是有道理的。所以其他基本上有一個右值,但本身就是一個左值。我對麼 ? – Rajeshwar 2015-03-31 19:10:17

+0

@Rajeshwar:我認爲引用是一個左值是稍微更準確的,因爲左值是從右值構造的。 (引用不是真正的「構建」,但你明白了) – 2015-03-31 19:41:08

+0

感謝您清除 – Rajeshwar 2015-03-31 19:52:07

0

在的情況下:

myfunct(std::string("dsdsd")); 

std::string("dsdsd")是一個範圍在調用myfunct()實際上是外內的暫時的。

C++明確指定將引用綁定到const會將臨時的生命週期延長到引用本身的生命週期。