C++11以上的新特性整理
阿新 • • 發佈:2018-11-06
1、nullptr
void foo(char *); void foo(int);
foo(NULL) //編譯出錯,不知道呼叫哪個,可能呼叫了foo(int)
foo(nullptr) //ok ,呼叫foo(char*)
//用nullptr替換原先的NULL
2、constexpr
#define LEN 10 int len_foo() { return 5; } int main() { char arr_1[10]; char arr_2[LEN]; int len = 5; char arr_3[len+5]; // 非法 const int len_2 = 10; char arr_4[len_2+5]; // 合法 char arr_5[len_foo()+5]; // 非法 return 0; } 改成:constexpr int len_foo() { return 5; } constexpr int len = 5;
3、auto 與 decltype用於型別推導
// 由於 cbegin() 將返回 vector<int>::const_iterator
// 所以 itr 也應該是 vector<int>::const_iterator 型別
for(auto itr = vec.cbegin(); itr != vec.cend(); ++itr);
auto x = 1; auto y = 2; decltype(x+y) z;
4、基於範圍的for迴圈
int array[] = {1,2,3,4,5}; for(auto &x : array) { std::cout<< x << std::endl; }
5、using的新用法,using可以替換typedef,可讀性更好,也更靈活
template <typename T,typename U,int value> class SuckType { public: T a; U b; SuckType():a(value),b(value){} }; template <typename U> using NewType = SuckType<int, U, 1>; //typedef不支援模板推導using Process = int(*)(void*); // 等效於 typedef int(*Process)(void*);
待新增----------------------------------------------------------------------------------------