auto搭配指針和引用
auto可化為推導(dǎo)后的類(lèi)型史汗,如果等號(hào)右邊是指針蛮艰,推導(dǎo)出來(lái)也帶指針,此時(shí)auto*和auto沒(méi)什么區(qū)別拒担,例如以下程序的c和d嘹屯;
但引用會(huì)在推導(dǎo)的過(guò)程中被“吃掉”,需要手動(dòng)在auto旁邊加上&从撼,例如以下程序的g和h州弟。
int main() {
int x;
int * y = &x;
double foo();
int & bar();
auto * a = &x; // int*
auto & b = x; // int
auto c = y; // int*
auto * d = y; // int*
auto * e = &foo(); // error: lvalue required as unary ‘&’ operand
auto & f = foo(); // error: invalid initialization of non-const reference of type ‘double&’ from an rvalue of type ‘double’
auto g = bar(); // int
auto & h = bar(); // int&
}
auto與cv限制符關(guān)系
cv限制符(cv-qualifier)是指const和volatile,常量的和易失的低零。
cv限制符可以加在auto的旁邊婆翔,但推導(dǎo)過(guò)程會(huì)“吃掉”等號(hào)右邊的cv限制符,用auto&可以防止等號(hào)右邊的cv被“吃掉”掏婶。
int main() {
double foo();
float * bar();
const auto a = foo(); // const double
const auto & b = foo(); // const double&
volatile auto * c = bar(); // volatile float*
auto d = a; // double
auto & e = a; // const double&
auto f = c; // float*
volatile auto & g = c; // volatile float * &
}
auto聲明多個(gè)變量
和其他變量指示符一樣啃奴,在一句話(huà)中,可以聲明多個(gè)變量雄妥,按第一個(gè)變量的推導(dǎo)結(jié)果為準(zhǔn)最蕾,后面幾個(gè)推導(dǎo)出來(lái)的類(lèi)型必須相同,如果不同就會(huì)報(bào)編譯錯(cuò)誤老厌。
int main() {
auto x = 1, y = 2;
const auto* m = &x, n = 1; // OK瘟则,auto推導(dǎo)出來(lái)用int替代,*是隨m的枝秤,沒(méi)有問(wèn)題
auto i = 1, j = 3.14f; // error: inconsistent deduction for ‘a(chǎn)uto’: ‘int’ and then ‘float’
auto o = 1, &p = o, *q = &p; // OK醋拧,從左到右推導(dǎo)
}
總結(jié)
有個(gè)方法可以比較直觀理解auto的規(guī)范,標(biāo)準(zhǔn)里稱(chēng)auto是一個(gè)將要推導(dǎo)出類(lèi)型的占位符(placeholder)淀弹,推導(dǎo)完了拿結(jié)果去提到auto的位置丹壕。