我隨機寫函數需要數組引用,並返回一個數組,並初始化從舊的新數組:這個數組的拷貝是如何工作的?
#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權?
另外爲什麼y
是double[4]
? auto&&
應該完美地轉發類型,y應該是double [4] &
對不對?
有人可以解釋爲什麼所有這些發生?
'auto y &&'?你是不是指'auto && y'? – ArtemGr
a []事實上是指向double的指針。 – Ashalynd
請發佈你想知道的實際代碼,而不是代碼是** close **你想知道的。我冒昧地提出'&&',我認爲這是一個錯誤的'旁邊'汽車' - 如果我錯了,請回復。 – Yakk