C++近年來加入了很多新特性,這些特性大大增強了語言的功能性、可讀性和效率。以下是開發中一些常用的C++新特性(從C++11到C++20),簡單總結,歡迎補充:
1. C++11
- 自動類型推導 (
auto
):可以自動推導變量類型,減少代碼冗余。
auto x = 42; // 自動推導為 int
- 范圍-based for 循環:簡化了對容器的遍歷。
for (auto& elem : container) { // 處理elem}
- 智能指針 (
std::unique_ptr
,std::shared_ptr
):用于自動管理內存,避免內存泄漏。
std::unique_ptr p = std::make_unique(10);
- Lambda 表達式:允許定義匿名函數,減少了代碼冗余。
auto lambda = [](int x) { return x * 2; };
- 并發 (
std::thread
,std::mutex
):增加了線程支持。
std::thread t([]() { /* 做一些工作 */ });t.join();
- 右值引用和移動語義:引入了
&&
和std::move
,優化了資源管理和性能。
void func(std::vector&& vec) { // 處理移動的資源}
2. C++14
- 自動推導返回類型 (
auto
返回類型):函數返回值類型可以使用auto
推導。
auto func() { return 42; }
- lambda 捕獲 by move:允許lambda按值捕獲并移動對象。
auto lambda = [x = std::move(my_object)]() { /* 使用x */ };
- std::make_unique:簡化了
unique_ptr
的創建。
auto p = std::make_unique(10);
3. C++17
- 結構化綁定聲明:可以解構元組、pair等。
auto [x, y] = std::make_pair(1, 2);
std::optional
:表示一個可能為空的值。
std::optional opt = 42;
std::filesystem
:標準庫增加了對文件系統的支持。
namespace fs = std::filesystem;for (const auto& entry : fs::directory_iterator("/path/to/dir")) { std::cout << entry.path() << std::endl;}
std::string_view
:提供了對字符串的輕量級非擁有視圖。
std::string_view str_view = "Hello, world!";
4. C++20
- 概念(Concepts):提供了類型約束,增強了模板的可讀性和可調試性。
template concept Incrementable = requires(T x) { ++x; };template void increment(T& x) { ++x; }
- 范圍庫(Ranges):簡化了對容器的操作,提供了管道式操作。
#include auto result = data | std::views::transform([](int x) { return x * 2; });
- 協程(Coroutines):用于簡化異步編程和生成器。
#include std::future get_data() { co_return 42;}
- 三向比較(Spaceship Operator
<=>
):簡化了比較操作符的編寫。
struct MyType { int x, y; auto operator<=>(const MyType&) const = default;};
std::span
:提供對數組或容器的輕量級視圖。
std::span span(arr, size);
consteval
和constinit
:分別用于在編譯時求值和初始化常量表達式。
consteval int square(int x) { return x * x; }
這些新特性讓C++變得更現代、簡潔且高效。你有興趣深入某一個特性或如何在項目中使用這些特性嗎?