【C++11】新特性——auto的使用

來源:互聯網
上載者:User

    C++11中引入的auto主要有兩種用途:自動類型推斷和傳回值佔位。auto在C++98中的標識臨時變數的語義,由於使用極少且多餘,在C++11中已被刪除。前後兩個標準的auto,完全是兩個概念。

1. 自動類型推斷

    auto自動類型推斷,用於從初始設定式中推斷出變數的資料類型。通過auto的自動類型推斷,可以大大簡化我們的編程工作。下面是一些使用auto的例子。

#include <vector>#include <map>using namespace std;int main(int argc, char *argv[], char *env[]){// auto a;                 // 錯誤,沒有初始設定式,無法推斷出a的類型// auto int a = 10;        // 錯誤,auto臨時變數的語義在C++11中已不存在, 這是舊標準的用法。// 1. 自動協助推導類型auto a = 10;auto c = 'A';auto s("hello");// 2. 類型冗長map<int, map<int,int> > map_;map<int, map<int,int>>::const_iterator itr1 = map_.begin();const auto itr2 = map_.begin();auto ptr = [](){std::cout << "hello world" << std::endl;};return 0;};// 3. 使用模板技術時,如果某個變數的類型依賴於模板參數,// 不使用auto將很難確定變數的類型(使用auto後,將由編譯器自動進行確定)。template <class T, class U>void Multiply(T t, U u){    auto v = t * u;}
2. 傳回值佔位

 

template <typename T1, typename T2>auto compose(T1 t1, T2 t2) -> decltype(t1 + t2){   return t1+t2;}auto v = compose(2, 3.14); // v's type is double

 

3.使用注意事項

①我們可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 來修飾auto

auto k = 5;auto* pK = new auto(k);auto** ppK = new auto(&k);const auto n = 6;

②用auto聲明的變數必須初始化

auto m; // m should be intialized  

③auto不能與其他類型組合連用

auto int p; // 這是舊auto的做法。

④函數和模板參數不能被聲明為auto

void MyFunction(auto parameter){} // no auto as method argumenttemplate<auto T> // utter nonsense - not allowedvoid Fun(T t){}

⑤定義在堆上的變數,使用了auto的運算式必須被初始化

int* p = new auto(0); //fineint* pp = new auto(); // should be initialized auto x = new auto(); // Hmmm ... no intializer   auto* y = new auto(9); // Fine. Here y is a int*auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)

⑥以為auto是一個預留位置,並不是一個他自己的類型,因此不能用於類型轉換或其他一些操作,如sizeof和typeid

int value = 123;auto x2 = (auto)value; // no casting using autoauto x3 = static_cast<auto>(value); // same as above 

⑦定義在一個auto序列的變數必須始終推導成同一類型

auto x1 = 5, x2 = 5.0, x3='r';  // This is too much....we cannot combine like this

⑧auto不能自動推導成CV-qualifiers(constant & volatile qualifiers),除非被聲明為參考型別

const int i = 99;auto j = i;       // j is int, rather than const intj = 100           // Fine. As j is not constant// Now let us try to have referenceauto& k = i;      // Now k is const int&k = 100;          // Error. k is constant// Similarly with volatile qualifer

⑨auto會退化成指向數組的指標,除非被聲明為引用

int a[9];auto j = a;cout<<typeid(j).name()<<endl; // This will print int*auto& k = a;cout<<typeid(k).name()<<endl; // This will print int [9]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.