一文詳解C++11中auto的使用
在C語言中,就有了auto關鍵字,它被當作是一個變量的存儲類型修飾符,表示自動變量(局部變量)。它不能被單獨使用,否則編譯器會給出警告。在C++11標準中,添加了新的類型推導特性。在C ++11中,使用auto定義的變量不能使用其它類型修飾符修飾,該變量的類型由編譯器根據(jù)初始化數(shù)據(jù)自動確定。
C++中類型檢查是在編譯階段。動態(tài)類型語言能做到在運行時決定類型,主要歸功于一技術,這技術是類型推導。在C++11中,可以通過重定義auto關鍵字來實現(xiàn)類型推導。
在C++11中,使用auto關鍵字可以要求編譯器對變量的類型進行自動推導。
auto關鍵字:類型推導,從該關鍵字的初始化表達式中推導變量的類型。
在塊作用域、命名空間作用域、for循環(huán)的初始化語句內聲明變量的時候,變量的類型可以被省略,使用關鍵字auto來代替。
auto聲明的變量必須被初始化,以使編譯器能夠從其初始化表達式中推導出其類型。
聲明為auto的變量在編譯時期就分配了內存,而不是到了運行時期,所以使用auto不再引發(fā)任何速度延遲,這也意味著使用auto的時候,這個變量不初始化會報錯,因為編譯器無法知道這個變量的類型。
auto使用時需注意:
(1)、可以使用const、volatile、pointer(*)、reference(&)、rvalue reference(&&)等說明符和聲明符來修飾auto關鍵字;
(2)、用auto聲明的變量必須初始化;
(3)、auto不能與其它任何類型說明符一起使用;
(4)、方法、參數(shù)或模板參數(shù)不能被聲明為auto;
(5)、定義在堆上的變量,使用了auto的表達式必須被初始化;
(6)、auto是一個占位符,不是類型,不能用于類型轉換或其它一些操作,如sizeof、typeid;
(7)、auto關鍵字內聲明的聲明符列表的所有符號必須解析為同一類型;
(8)、auto不能自動推導成CV-qualifiers(constant& volatile qualifiers),除非被聲明為引用類型;
(9)、auto會退化成指向數(shù)組的指針,除非被聲明為引用;
(10)、auto不能作為函數(shù)的返回類型,在C++14中是可以的。
建議:大多數(shù)情況使用關鍵字auto,除非非常需要轉換。
下面是從其他文章中copy的測試代碼,詳細內容介紹可以參考對應的reference:
#include "auto.hpp"
#include <iostream>
#include <cmath>
#include <typeinfo>
#include <string>
#include <map>
#include <list>
#include <deque>
#include <vector>
//
// reference: http://en.cppreference.com/w/cpp/language/auto
template<class T, class U>
auto add(T t, U u) -> decltype(t + u) // the return type is the type of operator+(T, U)
{
return t + u;
}
auto get_fun(int arg) -> double(*)(double) // same as: double (*get_fun(int))(double)
{
switch (arg) {
case 1: return std::fabs;
case 2: return std::sin;
default: return std::cos;
}
}
int test_auto1()
{
auto a = 1 + 2;
std::cout << "type of a: " << typeid(a).name() << '\n'; // type of a: int
auto b = add(1, 1.2);
std::cout << "type of b: " << typeid(b).name() << '\n'; // type of b: double
auto c = { 1, 2 };
std::cout << "type of c: " << typeid(c).name() << '\n'; // type of c: class std::initializer_list<int>
auto my_lambda = [](int x) { return x + 3; };
std::cout << "my_lambda: " << my_lambda(5) << '\n'; // my_lambda: 8
auto my_fun = get_fun(2);
std::cout << "type of my_fun: " << typeid(my_fun).name() << '\n'; // type of my_fun: double (__cdecl*)(double)
std::cout << "my_fun: " << my_fun(3) << '\n'; // my_fun: 0.14112
// auto int x; // error as of C++11: "auto" is no longer a storage-class specifier // error C3530: “auto”不能與任何其他類型說明符組合
return 0;
}
// reference: https://msdn.microsoft.com/zh-cn/library/dd293667(v=vs.120).aspx
int f(int x) { return x; }
int test_auto2()
{
int count = 10;
int& countRef = count;
auto myAuto = countRef;
countRef = 11;
std::cout << count << " " << std::endl; // 11
myAuto = 12;
std::cout << count << std::endl; // 11
// 1. 下面的聲明等效。 在第一個語句中,聲明 j 變量為類型 int。 在第二個語句,因為初始化表達式 (0) 是整數(shù),所以變量 k 推導為 int 類型
int j = 0; // Variable j is explicitly type int.
auto k = 0; // Variable k is implicitly type int because 0 is an integer.
// 2. 以下聲明等效,但第二個聲明比第一個簡單
std::map<int, std::list<std::string>> m;
std::map<int, std::list<std::string>>::iterator i = m.begin();
auto i_ = m.begin();
// 3. 聲明 iter 和 elem 變量類型
std::deque<double> dqDoubleData(10, 0.1);
for (auto iter = dqDoubleData.begin(); iter != dqDoubleData.end(); ++iter) { /* ... */}
// prefer range-for loops with the following information in mind
// (this applies to any range-for with auto, not just deque)
for (auto elem : dqDoubleData) // COPIES elements, not much better than the previous examples
{ /* ... */ }
for (auto& elem : dqDoubleData) // observes and/or modifies elements IN-PLACE
{ /* ... */ }
for (const auto& elem : dqDoubleData) // observes elements IN-PLACE
{ /* ... */ }
// 4. 使用 new 運算符
double x = 12.34;
auto *y = new auto(x), **z = new auto(&x);
// 5. 所有符號解析為同一類型
auto x_ = 1, *y_ = &x_, **z_ = &y_; // Resolves to int.
auto a(2.01), *b(&a); // Resolves to double.
auto c = 'a', *d(&c); // Resolves to char.
auto m_ = 1, &n_ = m_; // Resolves to int.
// 6. 使用條件運算符 (?:)
int v1 = 100, v2 = 200;
auto e = v1 > v2 ? v1 : v2;
// 7. 將變量 x7 初始化類型 int,將引用的變量 y7 初始化為類型 const int,及將變量 fp 初始化為指向返回類型 int 的函數(shù)的指針
auto x7 = f(0);
const auto & y7 = f(1);
int(*p)(int x7);
p = f;
auto fp = p;
return 0;
}
/
// reference: http://www.learncpp.com/cpp-tutorial/4-8-the-auto-keyword/
int add_3(int x, int y)
{
return x + y;
}
int test_auto3()
{
auto d = 5.0; // 5.0 is a double literal, so d will be type double
auto i = 1 + 2; // 1 + 2 evaluates to an integer, so i will be type int
auto sum = add_3(5, 6); // add_3() returns an int, so sum will be type int
return 0;
}GitHub:https://github.com/fengbingchun/Messy_Test
到此這篇關于一文詳解C++11中auto的使用的文章就介紹到這了,更多相關C++11 auto內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VC程序在Win32環(huán)境下動態(tài)鏈接庫(DLL)編程原理
這篇文章主要介紹了VC程序在Win32環(huán)境下動態(tài)鏈接庫(DLL)編程原理,包括了dll文件的原理與具體實現(xiàn)過程,對于深入掌握VC程序設計具有很好的參考借鑒價值,需要的朋友可以參考下2014-10-10
C/C++ Windows SAPI實現(xiàn)文字轉語音功能
本文通過封裝Windows SAPI(Speech Application Programming Interface),提供了一個現(xiàn)代化的C++接口實現(xiàn)文字轉語音功能,這篇文章重點給大家介紹C/C++ Windows SAPI自實現(xiàn)文字轉語音功能,感興趣的朋友一起看看吧2025-02-02
C++編寫DLL動態(tài)鏈接庫的步驟與實現(xiàn)方法
這篇文章主要介紹了C++編寫DLL動態(tài)鏈接庫的步驟與實現(xiàn)方法,結合實例形式分析了C++導出類文件及生成與調用DLL動態(tài)連接庫的相關操作技巧,需要的朋友可以參考下2016-08-08
一文詳解C++關鍵字nullptr及與NULL的區(qū)別
這篇文章主要給大家詳細介紹了C++關鍵字nullptr,及?NULL與nullptr的區(qū)別,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-06-06

