C++11、C++14、C++17、C++20常用新特性
C++11
自動類型推斷(auto關(guān)鍵字):C++11引入了auto關(guān)鍵字,可以根據(jù)變量初始值自動推導(dǎo)出變量類型。例如:
auto i = 42; // i被推導(dǎo)為int類型 auto d = 3.14; // d被推導(dǎo)為double類型
基于范圍的for循環(huán)(range-based for loop):可以方便地遍歷容器中的元素,例如:
std::vector<int> v = {1, 2, 3, 4, 5}; for (auto& i : v) { i *= 2; }
lambda表達式:lambda表達式可以用來定義匿名函數(shù),方便地傳遞函數(shù)對象,例如:
auto f = [](int x, int y) -> int { return x + y; }; int result = f(3, 4); // result = 7
移動語義和右值引用(move semantics和rvalue references):通過右值引用可以實現(xiàn)資源的有效移動而不是復(fù)制,提高程序的效率,例如:
std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = std::move(v1); // v2接管了v1的資源,v1變?yōu)闊o效狀態(tài)
智能指針(smart pointers):C++11引入了三種智能指針:unique_ptr、shared_ptr和weak_ptr,可以更好地管理動態(tài)內(nèi)存,避免內(nèi)存泄漏和懸空指針,例如:
std::unique_ptr<int> p(new int(42)); std::shared_ptr<int> q = std::make_shared<int>(42); std::weak_ptr<int> r = q;
空指針常量(nullptr):C++11引入了nullptr關(guān)鍵字,用于表示空指針,避免了NULL宏帶來的一些問題,例如:
void f(int* p) {} f(nullptr); // 可以顯式地傳遞空指針
右值引用與移動構(gòu)造函數(shù):右值引用可以方便地實現(xiàn)移動構(gòu)造函數(shù)和移動賦值運算符,用于高效地處理臨時對象和避免復(fù)制開銷,例如:
class MyVector { public: MyVector(MyVector&& other) noexcept { // 移動構(gòu)造函數(shù) } MyVector& operator=(MyVector&& other) noexcept { // 移動賦值運算符 return *this; } };
初始化列表:可以方便地初始化數(shù)組和容器,例如:
std::vector<int> v = {1, 2, 3, 4, 5}; std::map<std::string, int> m = {{"one", 1}, {"two", 2}, {"three", 3}};
類型別名(type alias):可以使用using關(guān)鍵字定義類型別名,例如:
using IntVec = std::vector<int>; IntVec v = {1, 2, 3, 4, 5};
模板別名(template alias):可以使用using關(guān)鍵字定義模板別名,例如:
template <typename T> using Vec = std::vector<T>; Vec<int> v = {1, 2, 3, 4, 5};
constexpr函數(shù)和變量:可以在編譯期計算出值,例如:
constexpr int fib(int n) { return (n <= 1) ? 1 : fib(n-1) + fib(n-2); } constexpr int x = fib(10); // 編譯期計算出x的值為89
變長參數(shù)模板(variadic templates):可以接受任意數(shù)量和類型的參數(shù),例如:
template <typename... Args> void print(Args... args) { std::cout << sizeof...(args) << std::endl; // 打印參數(shù)個數(shù) } print(1, 2, 3); // 打印3 print("hello", 3.14); // 打印2
C++14
泛型lambda表達式:可以使用auto關(guān)鍵字在lambda表達式中推斷參數(shù)類型,例如:
auto sum = [](auto x, auto y) { return x + y; }; std::cout << sum(1, 2) << std::endl; // 輸出3 std::cout << sum(1.5, 2.5) << std::endl; // 輸出4.0
return type deduction for normal functions(函數(shù)返回類型推斷):可以使用auto關(guān)鍵字讓編譯器自動推斷函數(shù)的返回類型,例如:
auto add(int x, int y) { return x + y; // 返回類型會自動推斷為int }
模板變量(template variable):可以使用關(guān)鍵字template定義模板變量,例如:
template <typename T> constexpr T pi = T(3.1415926535897932385); std::cout << pi<double> << std::endl; // 輸出3.14159...
靜態(tài)斷言(static_assert)的增強:可以在靜態(tài)斷言中加入一個字符串提示,例如:
static_assert(sizeof(int) == 4, "int必須是4字節(jié)"); // 如果sizeof(int)不等于4,會輸出提示信息
字符串字面量的增強:可以使用單引號(')包圍字符,例如:
constexpr char operator""_c(char c) { return c; } // 將字符轉(zhuǎn)化為字符 std::cout << 'a'_c << std::endl; // 輸出字符'a'
按值捕獲的增強:可以使用關(guān)鍵字init來對按值捕獲的變量進行初始化,例如:
int x = 1, y = 2; auto f = [x, y = x + 1] { return x + y; }; std::cout << f() << std::endl; // 輸出4
變量模板(variable template):可以使用關(guān)鍵字template定義變量模板,例如:
template <typename T> constexpr T pi = T(3.1415926535897932385); std::cout << pi<double> << std::endl; // 輸出3.14159...
內(nèi)存模型的增強:增加了對內(nèi)存模型的規(guī)定,例如:
std::atomic<int> x = 0; // 原子變量 #pragma omp parallel for for (int i = 0; i < 1000; ++i) { x.fetch_add(1); // 線程安全的對x進行加一操作 } std::cout << x << std::endl; // 輸出1000
C++17
結(jié)構(gòu)化綁定(Structured Binding):可以使用auto關(guān)鍵字對一個結(jié)構(gòu)體或元組進行結(jié)構(gòu)化綁定,例如:
std::pair<int, int> p = {1, 2}; auto [x, y] = p; // 結(jié)構(gòu)化綁定 std::cout << x << " " << y << std::endl; // 輸出1 2
if語句和switch語句的初始化:可以在if語句和switch語句的判斷條件中進行變量初始化,例如:
if (int x = get_value(); x > 0) { // 在if語句中初始化變量x std::cout << "x is positive" << std::endl; }
類模板的參數(shù)推斷(Class Template Argument Deduction,CTAD):可以讓編譯器自動推斷類模板的模板參數(shù),例如:
std::pair p{1, 2}; // 編譯器可以自動推斷出std::pair<int, int>
constexpr if:可以在編譯期進行條件判斷,根據(jù)判斷結(jié)果選擇不同的代碼路徑,例如:
template <typename T> void foo(T t) { if constexpr (std::is_pointer_v<T>) { // 如果T是指針類型 std::cout << "t is a pointer" << std::endl; } else { // 如果T不是指針類型 std::cout << "t is not a pointer" << std::endl; } }
折疊表達式(Fold Expression):可以使用折疊表達式來簡化代碼,例如:
template <typename... Args> auto sum(Args... args) { return (args + ...); // 對args進行折疊求和 } std::cout << sum(1, 2, 3, 4) << std::endl; // 輸出10
內(nèi)聯(lián)變量(Inline Variable):可以使用inline關(guān)鍵字來定義內(nèi)聯(lián)變量,例如:
inline int x = 1; // 定義一個內(nèi)聯(lián)變量x,初始值為1
嵌套命名空間(Nested Namespace):可以在命名空間中嵌套命名空間,例如:
namespace A { namespace B { void foo() { std::cout << "hello, world!" << std::endl; } } } A::B::foo(); // 調(diào)用函數(shù)foo
C++20
概念(Concepts):概念是一種新的語言結(jié)構(gòu),可以用來描述模板參數(shù)的要求,例如:
template <typename T> concept Integral = std::is_integral_v<T>; template <typename T> void foo(T t) requires Integral<T> { // 使用概念描述模板參數(shù)要求 std::cout << t << std::endl; } foo(1); // 調(diào)用foo函數(shù)
三方合并運算符(Three-way Comparison Operator):可以使用<=>運算符對兩個對象進行三方比較,例如:
struct Point { int x, y; auto operator<=>(const Point& other) const { return std::tie(x, y) <=> std::tie(other.x, other.y); } }; bool operator==(const Point& lhs, const Point& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } std::set<Point> s{{1, 2}, {2, 1}, {1, 1}, {2, 2}}; for (const auto& p : s) { std::cout << p.x << ", " << p.y << std::endl; }
輸出結(jié)果為:
1, 1
1, 2
2, 1
2, 2
初始化的捕獲列表(Init-Capture):可以在lambda表達式的捕獲列表中進行初始化,例如:
int x = 1; auto lambda = [value = x * 2]() { // 在捕獲列表中初始化變量value std::cout << value << std::endl; }; lambda(); // 調(diào)用lambda表達式
consteval函數(shù):可以在編譯期計算表達式的值,例如:
consteval int get_value() { return 42; } // 定義一個在編譯期計算的函數(shù) std::array<int, get_value()> arr; // 在編譯期創(chuàng)建一個大小為42的數(shù)組
模塊(Modules):可以使用模塊來管理和組織代碼,替代傳統(tǒng)的頭文件包含方式,例如:
// 定義一個模塊 module my_module; export void foo() { std::cout << "hello, world!" << std::endl; } // 使用模塊 import my_module; int main() { foo(); // 調(diào)用函數(shù)foo return 0; }
到此這篇關(guān)于C++11、C++14、C++17、C++20常用新特性的文章就介紹到這了,更多相關(guān)C++11、C++14、C++17、C++20新特性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++中的數(shù)字轉(zhuǎn)字符串to_string
這篇文章主要介紹了C++中的數(shù)字轉(zhuǎn)字符串to_string,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11