C++日記——Day61:auto類型推斷,auto應用場合

特點:

1、auto自動類型推斷髮生在編譯期,所以不會影響程序執行期間的性能;

2、auto定義變量必須立即初始化,這樣編譯器才能推斷它的實際類型。那麼編譯的時候才能確定auto的類型和整個變量的類型,然後在編譯期間就可以用真正的類型替換掉auto這個類型佔位符。

3、auto的使用靈活,和指針 和引用 和const 等限定符結合使用。

 

auto類型推導出來一個具體類型。auto實際上是一個類型,那麼這裏的auto實際上就相當於模板函數推導裏邊的類型模板參數T。所以auto這個東西也是類型聲明的一部分。

a)傳值方式(非指針,非引用):傳值時引用類型會被拋棄,const屬性也會被拋棄,對方看成新副本

auto x = 27;
const auto x2 = x;

b)指針或者引用類型但不是萬能引用,不會拋棄const等限定符,但是會丟棄引用

const auto &xy = x; // xy = const int & , auto = int
auto xy2 = xy;  //xy2 = int, auto = int  傳值時引用類型會被拋棄,const屬性也會被拋棄,對方看成新副本

auto &xy3 = xy; //xy3 = const int &, auto = const int ,引用被丟棄,但const屬性會保留,(因爲此處爲 &xy3,所以auto會繼承const屬性)

auto y = new auto(100);

const auto *xp = &x; //xp = const int *, auto = int

auto *xp2 = &x; xp2 = int *, auto = int;

auto xp3 = &x; //xp3 = int *, auto = int *

 

c)萬能引用類型

int x = 19;
auto&& wnyy1 = x; // x是左值, auto = int &, wnyy1 = int &
auto&& wnyy2 = x2; // x2是左值,auto = int& , wnyy2 = const int &
auto&& wnyy3 = 100; // auto = int ,wnyy3 = int &&

 

三:auto針對數組和函數的推斷

const char mystr[] = "I love China";
auto myarr = mystr; // const char * 
auto &myarr2 = mystr; // const char (&)[14] 這裏變成了數組的引用,應該是此處mystr不代表字符串數組的首地址了


int a[2] = {1, 2};
auto aauto = a; // aauto = int * , auto = int *


void myfunc3
{

}

auto tmpf = myfunc3; // void (*) (double, int) 函數指針
auto &tmpf2 = myfunc3; //void (&) (double, int) 函數引用

 

四、std::initializer_list<int>

auto x = 10; // int
auto x2(20); // int 
auto x3 = {39}; // std::initializer_list<int> 這是一個針對auto的特殊推倒
auto x4{12}; // int

auto遇到 = {} 時推倒規則就不一樣了。

std::initializer_list<int> C++11引入的新類型,表示某種特定的值得數組。這種推倒指適用於auto,不適合模板類型。這一點是auto類型推倒和模板推倒的區別之處。

 

auto func()
{
    return 12; // 也可以
}

 auto還可以放在函數返回類型的位置上。

 

class CT{
public:
    auto m_i = 12; //報錯,普通成員變量不能是auto類型。
    static const auto m_si = 15; //static const可以使用auto,其值必須在類內初始化              
}

void func(void x, int y){

}

 

auto不適用場合:

1、auto不能用於函數參數

2、普通成員變量不可以是auto類型

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章