1、C++11常用特性介紹
從本篇開始介紹C++11常用特性,大致分:關鍵字及新語法、STL容器、多線程、智能指針內存管理,最後講一下std::bind和std::function
二、關鍵字和新語法
1)auto類型修飾符,可以根據初始化代碼的內容自動判斷變量的類型,而不是顯式的指定,如:
auto a = 1;
auto b = 'A';
由於1的類型是int,所以a的類型就是int;同樣由於'A'的類型是char,所以b的類型是char。
如果只是將auto用在變量聲明,那將是毫無意義的,auto主要用在遍歷。如:
a)遍歷字符串
std::string str = "hello world";
for(auto ch : str)
{
std::cout << ch << std::endl;
}
b)遍歷數組
int array[] = {1,2,3,4,5,6,7,8,9};
for(auto i : array)
{
std::cout << i << std::endl;
}
c)遍歷vector容器
std::vector<int> vect = {1,2,3,4,5,6,7,8,9};
for(auto i : vect)
{
std::cout << i << std::endl;
}
d)遍歷map容器
std::map<int,int> map = {{1,1}, {2,2}, {3,3}};
for(auto iter : map)
{
std::cout << iter.first << iter.second << std::endl;
}
auto的使用為遍歷提供了很大的便利,再也不用寫那麼長的for循環。
e)定義依賴模板參數的變量類型的模板函數
template <typename _T1,typename _T2>
void Addition(_T1 t1,_T2 t2)
{
auto v = t1 + t2;
std::cout << v << std::endl;
}
f)定義函數返回值依賴模板參數的變量類型的模板函數
template <typename _T1,typename _T2>
auto Addition(_T1 t1,_T2 t2)->decltype(t1 * t2)
{
return t1 * t2;
}
2)注意事項
a)auto變量必須在定義時初始化,類似於const關鍵字。
b)定義一個auto序列的變量必須始終推導成同一類型,如:
auto a=1,b=2,c=3; //正確
auto a=1,b=1.1,c='c'; //錯誤
c)如果初始化表達式是引用,則去除引用語義,如:
int a = 1;
int &b = a;
auto c = b; //c的類型為int而非int&(去除引用)
auto &d= b; //d的類型為int&
c = 100; //a = 1;
d = 100; //a = 100;
d)如果初始化表達式為const或volatile(或者兩者兼有),則除去const/volatile語義,如:
const int a = 1;
auto b = a; //b的類型為int而非const int(去除const)
auto &c = a; //c的類型為const int
const auto d = a;//d的類型為const int
b = 100; //合法
c = 100; //非法
d = 100; //非法
e)初始化表達式為數組時,auto關鍵字推導類型為指針
int a[] = {1,2,3,4,5};
auto b = a;
std::cout << typeid(b).name() << std::endl;//輸出int[5];
f)不能作為一些以類型為操作數的操作符的操作數,如sizeof或者typeid:
std::cout << sizeof(auto) << std::endl; //錯誤
std::cout << typeid(auto).name() << std::endl; //錯誤
g)函數參數或者模板參數不能被聲明為auto,如:
template <auto T>
void Addition(auto a,T t)
{
}