auto:C++11標準引入的類型說明符,編譯器通過初始值來推算變量的類型。因此,auto定義的變量必須有初始值
auto類型和初始值的類型并不完全一樣,編譯器會適當的改變結果類型使其更符合初始化規則
- 引用為初始值時,引用對象的類型為auto類型
int i=0, &r=i;
auto a = r ; //a是一個整數(int類型) - 忽略頂層const,保留底層const
const int ci = i, &cr = ci;
auto b = ci; //b是一個整數,const特性被忽略
auto c = cr; //c是一個整數
auto d = &i; //d是一個int*
auto e = &ci; //e是一個const int *,變為底層const
如果希望auto類型是一個頂層const
const auto f = ci; //f是const int
auto &m = ci, *p = &ci; //m是const int&, p是const int *
decltype:C++11從表達式的類型推斷出要定義的變量的類型,并不實際計算表達式的值
- decltype返回變量的類型,包括頂層const和引用在內
const int ci=0, &cj = ci;
decltype(ci) x = 0; //x的類型是const int
decltype(cj) y = x; //y的類型是const int&, 必須被初始化 - decltype使用的表達式不是變量,就返回結果對應的類型
int i=42, p=&i, &r=i;
decltype(r+0) b; //b是未初始化的int
decltype(p) c; //c是int&,必須被初始化,解引用操作將得到引用類型,因為解引用指針可以得到指針所指的對象,而且還能賦值 - 如果在變量名上加括號,會當做表達式,變量可以作為賦值語句左值,因此decltype會得到引用類型
decltype((i)) d; //d是int&, 必須被初始化 - decltype作用于某個函數時,返回函數類型而非指針
string::size_type sumLength(const string&, const string&);
decltype(sumLength) *getFunc(const string&) //如果不加指針,編譯報錯,返回值必須為函數指針,不能為函數類型,且不會自動轉換成指針。而作為參數是可以的,因為會隱式轉換為指針