2014-02-25 33 views
1

我隨機寫函數需要數組引用,並返回一個數組,並初始化從舊的新數組:這個數組的拷貝是如何工作的?

#include <iterator> 
#include <iostream> 

using namespace std; 

template <typename T> 
T& return_arr(T& arr) { 
    return arr; 
} 

int main(){ 
    double a[] = {1,2,4.5,9}; 
    auto x = return_arr(a); 
    a[2] = 5; 
    cout << x[2] << endl; 
    //x.dummy_error(); // If this one is uncommented, the compiler says x is a double* 
    auto&& y = return_arr(a); 
    a[3] = 10; 
    cout << y[3] << endl; 
    //y.dummy_error(); // If this one is uncommented, the compiler says y is a double[4] 

    return 0; 
} 

爲什麼x得到了腐朽的指針?該函數應該返回一個T&auto應該初始化一個類型T權?

另外爲什麼ydouble[4]auto&&應該完美地轉發類型,y應該是double [4] &對不對?

有人可以解釋爲什麼所有這些發生?

+1

'auto y &&'?你是不是指'auto && y'? – ArtemGr

+0

a []事實上是指向double的指針。 – Ashalynd

+0

請發佈你想知道的實際代碼,而不是代碼是** close **你想知道的。我冒昧地提出'&&',我認爲這是一個錯誤的'旁邊'汽車' - 如果我錯了,請回復。 – Yakk

回答

6

您不能在C++中按值傳遞或返回數組。對不起---你不能。

auto x = return_arr(a); 

在這個調用,T推導爲double [4]。所以return_arr需要參考數組,它也返回參考數組。所以這個電話確實同樣的事情

auto x = a; 

x推導爲double*。這是因爲auto使用與模板相同的類型推導規則,並且當參數是數組時,非參考模板類型參數被推斷爲指針。換句話說,衰變發生在這裏,正如你通常所期望的那樣。

auto&& y = return_arr(a); 

在這種情況下,由於參考,y推導作爲參考陣列和衰減不會發生。所以這與

double (&y)[4] = a; 

是一樣的,這是一個參考初始化。同樣,數組不會被複制。

如果要複製陣列,使用memsetstd::copy,或容器如std::vectorstd::array

+0

編譯器說y是'double [4]',而不是'double&[4]'... – texasbruce

+0

@texasbruce怎麼會這樣? – Brian

+0

我使用了'y.dummy_error()',並且編譯器說'錯誤:'y'中的成員'dummy_error'的請求,它是非類類型的'double [4]'' – texasbruce