Συνοπτικός οδηγός C++
Μια αναζητήσιμη, εκτυπώσιμη αναφορά σύγχρονης C++: smart pointers, containers, algorithms, RAII, move semantics, templates και concurrency. Δωρεάν.
Basics, auto & references
11auto x = 42;
const auto& r = bigObject;
int& ref = x; ref = 5;
constexpr int N = 10;
using Ids = std::vector<int>;
auto [key, value] = *map.begin();
if (auto it = m.find(k); it != m.end())
enum class Color { Red, Green };
nullptr
static_cast<int>(3.99)
std::int64_t n = 0; // <cstdint>
Smart pointers
10auto p = std::make_unique<Widget>(args);
auto s = std::make_shared<Widget>();
std::unique_ptr<Widget> q = std::move(p);
std::weak_ptr<Widget> w = s;
if (auto sp = w.lock()) sp->run();
p.get()
p.reset();
s.use_count()
void observe(const Widget& w);
std::unique_ptr<T[]> a = std::make_unique<T[]>(n);
Containers
12std::vector<int> v{1, 2, 3};
v.push_back(4); v.emplace_back(args);
v.reserve(1000);
std::map<std::string, int> m;
std::unordered_map<std::string, int> h;
m["hits"] += 1; m.at("hits");
if (m.contains(key)) ...
std::array<int, 3> a{1, 2, 3};
void f(std::span<const int> s);
std::set<int> s; std::unordered_set<int> u;
std::erase_if(v, [](int n) { return n < 0; });
v.size(); v.empty(); v.clear();
Algorithms & ranges
12std::ranges::sort(v);
std::sort(v.begin(), v.end(), cmp);
auto it = std::ranges::find_if(v, pred);
std::transform(v.begin(), v.end(), out, f);
std::accumulate(v.begin(), v.end(), 0)
std::ranges::count_if(v, pred)
v | std::views::filter(isEven)
| std::views::transform(square)
std::views::iota(0, 10)
auto v2 = r | std::ranges::to<std::vector>();
std::ranges::max_element(v)
std::ranges::any_of(v, pred)
Strings & string_view
11std::string s = "hi"; s += "!";
void f(std::string_view sv);
if (s.find("x") != std::string::npos)
s.substr(1, 3)
s.starts_with("http"); s.ends_with(".h");
s.contains("needle")
std::to_string(42)
int n = std::stoi("42");
std::format("{}: {}", key, count)
std::getline(std::cin, line);
R"(C:\path\no "escapes")"
Classes & RAII
11struct Point { int x = 0; int y = 0; };
Widget() : size_{0}, name_{"w"} {}
~Widget() { close(handle_); }
ctor, dtor, copy ctor/=, move ctor/=
Widget(const Widget&) = delete;
Widget(Widget&&) noexcept = default;
explicit Widget(int size);
int size() const { return size_; }
virtual void draw(); / void draw() override;
virtual ~Base() = default;
[[nodiscard]] bool ok() const;
Move semantics
9auto b = std::move(a);
Widget(Widget&& o) noexcept;
return result;
void set(std::string s) { s_ = std::move(s); }
v.push_back(std::move(str));
auto old = std::exchange(ptr_, nullptr);
std::swap(a, b);
// moved-from: valid but unspecified
template <class T> void f(T&& x) { g(std::forward<T>(x)); }
Templates & concepts
10template <typename T> T maxOf(T a, T b);
template <std::integral T> T half(T n);
template <class T> concept Number = std::is_arithmetic_v<T>;
void print(const auto& x);
if constexpr (std::is_integral_v<T>)
std::pair p{1, 2.5};
template <typename... Args> void log(Args&&... args);
(args + ...)
template <class T> requires Number<T> T sq(T x);
template <> struct Hash<Key> { ... };
Lambdas & std::function
10auto twice = [](int x) { return x * 2; };
[=] captures copies; [&] captures refs
[x, &total](int n) { total += x * n; }
[this] { return counter_; }
[p = std::move(ptr)] { p->run(); }
[n = 0]() mutable { return ++n; }
[](auto a, auto b) { return a < b; }
[](int x) -> double { return x / 2.0; }
std::function<int(int)> cb = twice;
std::ranges::sort(v, {}, &User::age);
Error handling
11std::optional<int> parse(std::string_view s);
opt.value_or(0)
if (opt) use(*opt);
std::expected<Data, Error> load();
res.and_then(step).transform(format)
throw std::runtime_error("bad config");
catch (const std::exception& e) { e.what(); }
void close() noexcept;
assert(ptr != nullptr);
static_assert(sizeof(int) == 4);
std::variant<int, Err> v; std::visit(fn, v);
Concurrency
10std::jthread t(work);
std::thread t(work); t.join();
std::mutex m; std::lock_guard lock(m);
std::scoped_lock lock(m1, m2);
std::unique_lock lk(m); cv.wait(lk, ready);
std::atomic<int> hits{0}; ++hits;
auto f = std::async(std::launch::async, fetch);
auto result = f.get();
std::this_thread::sleep_for(100ms);
thread_local int cache = 0;
Compilation & CMake
11g++ -std=c++23 -Wall -Wextra -O2 main.cpp -o app
clang++ -std=c++20 main.cpp -o app
-g -O0
-fsanitize=address,undefined
-Iinclude -Llib -lfoo
-DNDEBUG
cmake_minimum_required(VERSION 3.20)
add_executable(app main.cpp)
target_compile_features(app PRIVATE cxx_std_23)
cmake -B build && cmake --build build
cmake --build build -j 8
Καμία καταχώριση δεν ταιριάζει με «:q».
Σχετικά με το Συνοπτικός οδηγός C++
Αυτό το cheat sheet C++ συγκεντρώνει τη σύγχρονη C++ σε μία αναζητήσιμη αναφορά: βασικά με auto και references, smart pointers, containers, algorithms και ranges, strings και string_view, κλάσεις και RAII, move semantics, templates και concepts, lambdas και std::function, χειρισμό σφαλμάτων, ταυτοχρονισμό, και μεταγλώττιση με CMake.
It is aimed at the C++ people actually write today: unique_ptr and shared_ptr instead of raw new and delete, range-based algorithms, structured bindings, concepts on templates, std::thread and std::mutex; while still spelling out the fundamentals like the rule of five and RAII.
Όπως κάθε cheat sheet σε αυτή την ομάδα, είναι δωρεάν και client-side: φιλτράρετε γραμμές ζωντανά με το πλαίσιο αναζήτησης, μεταβείτε ανάμεσα σε τμήματα από τον σταθερό πίνακα περιεχομένων, αντιγράψτε οποιοδήποτε απόσπασμα με ένα κλικ και εκτυπώστε τη σελίδα ως αναφορά γραφείου.
Πώς να χρησιμοποιήσετε το Συνοπτικός οδηγός C++
- Ανοίξτε το φύλλο και εξετάστε τα τμήματα, από τα Βασικά, auto & references έως τη Μεταγλώττιση & CMake.
- Αναζητήστε μια λέξη-κλειδί όπως unique_ptr, ranges ή concept για να φιλτράρετε το φύλλο ζωντανά.
- Μεταβείτε στα Move semantics ή στα Templates & concepts όταν χρειάζεστε την πιο δύσκολη σύνταξη αναλυμένη.
- Κάντε κλικ σε ένα απόσπασμα ή στο εικονίδιο αντιγραφής του για να αντιγράψετε τον κώδικα C++ στο πρόχειρό σας.
- Χρησιμοποιήστε την Εκτύπωση για ένα χάρτινο αντίγραφο της πλήρους αναφοράς C++.