Modern C++
Quick Notes
Section titled “Quick Notes”Modern C++ ưu tiên RAII, type safety và abstraction không tốn runtime overhead.
Các bản C++11/14/17/20 thêm nhiều công cụ giúp code ngắn và an toàn hơn.
Khi compile, chỉ định standard rõ ràng như -std=c++20.
Syntax
Section titled “Syntax”auto [key, value] = *map.begin();std::optional<int> answer = findAnswer();auto x = 42;int* p = nullptr;
std::vector<int> v = {1, 2, 3};for (int value : v) { std::cout << value << '\n';}
auto square = [](int n) { return n * n; };auto add = [](auto a, auto b) { return a + b;};std::map<std::string, int> freq = {{"cpp", 20}};
for (const auto& [word, count] : freq) { std::cout << word << ": " << count << '\n';}
std::optional<int> value = 10;if (value) { std::cout << *value << '\n';}template<typename T>concept Number = std::integral<T> || std::floating_point<T>;
Number auto twice(Number auto x){ return x + x;}
std::span<int> view(values);Feature Map
Section titled “Feature Map”| Version | Features |
|---|---|
| C++11 | auto, lambda, nullptr, range-for, move semantics |
| C++14 | generic lambda, variable templates, relaxed constexpr |
| C++17 | structured bindings, optional, variant, filesystem |
| C++20 | concepts, ranges, span, coroutines, modules |
Common Mistakes
Section titled “Common Mistakes”- Dùng tính năng C++20 nhưng compile với
-std=c++17. - Lạm dụng
autokhiến API khó đọc. - Dùng
std::optional<T>nhưng vẫn gọi.value()không kiểm tra.
Search Keywords
Section titled “Search Keywords”modern c++ c++ hiện đại c++11 c++14 c++17 c++20 auto lambda nullptr structured bindings optional variant filesystem concepts ranges span