基於《C++14 Quick Syntax Reference》整理,記錄 C++11/14 引入的實用新特性。測試環境:GCC 5.3.0。
int oct = 062; // 八進制(舊)
int hex = 0x32; // 十六進制(舊)
int bin = 0b00110010; // 二進制(C++14 新增)
int longBin = 0b1010'0101'1010'0101; // 單引號分隔符(C++14)
nullptr(C++11)
int* p = nullptr; // 類型安全,非整數 0
nullptr_t mynull = nullptr; // 具體類型 nullptr_t
int&& ref = 1 + 2; // 綁定臨時對象
ref += 3; // 可修改
std::cout << ref; // 6
核心:避免不必要的拷貝,實現資源轉移。
// 傳統轉義
std::string escaped = "c:\\Windows\\System32\\cmd.exe";
// 原生字符串
std::string raw = R"(c:\Windows\System32\cmd.exe)";
// 正則表達式極大簡化
char regex[] = R"((?:'(?:[^\\']|\\.)*'|"(?:[^\\"]|\\.)*"))";
char16_t c16 = u'中'; // UTF-16
char32_t c32 = U'中'; // UTF-32
std::string s8 = u8"UTF-8";
std::u16string s16 = u"UTF-16";
std::u32string s32 = U"UTF-32";
int a[3] = {1,2,3};
for (int& x : a) std::cout << x; // 引用可修改
for (auto& x : vec) std::cout << x; // 推薦 auto&
auto 與 decltype(C++11/14)
auto i = 5; // int
auto d = 3.14; // double
auto b = false; // bool
int& ref = i;
auto copy = ref; // int (值拷貝)
auto& ref2 = ref; // int& (保留引用)
decltype(3) x = 3; // int&& (字面量是右值)
decltype((3)) y = 3; // int& (括號表達式是左值)
// C++14 返回類型推導
auto getValue(int x) { return x; } // 自動推導返回 int
decltype(auto) getRef(int& x) { return x; } // 保留引用類型
// 基本語法
auto sum = [](int x, int y) { return x + y; }; // 返回類型自動推導
std::cout << sum(2, 3); // 5
// 作為參數傳遞
void call(int arg, std::function func) { func(arg); }
call(2, [](int x) { std::cout << x*x; }); // 4
// 捕獲列表 []
int i = 2;
auto printSquare = [i]() { std::cout << i*i; }; // 值捕獲,只讀
// [i]() mutable { i++; ... } // mutable 允許修改副本
// 引用捕獲
int a = 1;
[&a](int x) { a = x*x; }(12); // a 變為 144
// C++14 泛型 Lambda
auto add = [](auto x, auto y) { return x + y; };
add(2, 3); add(2.2, 3.0); add(2.2, 3);
// C++14 初始化捕獲
int x = 1;
[&, y = 2]() { x += y; }(); // x 變為 3
auto/decltype 減少冗長類型聲明,配合範圍 for 極大提升可讀性std::bind下篇將介紹類與對象的新特性:委託構造、繼承構造、刪除函數、final/override 等。