Karatasi ya Muhtasari ya C++
Rejeo la C++ ya kisasa linalotafutika na kuchapishika: smart pointers, containers, algorithms, RAII, move semantics, templates na concurrency. Bure.
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
Hakuna kipengele kinacholingana na “:q”.
Kuhusu Karatasi ya Muhtasari ya C++
Karatasi hii ya muhtasari ya C++ inakusanya C++ ya kisasa kwenye rejeo moja linalotafutika: misingi yenye auto na references, smart pointers, containers, algorithms na ranges, strings na string_view, classes na RAII, move semantics, templates na concepts, lambdas na std::function, ushughulikiaji wa makosa, concurrency, na ukusanyaji kwa 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.
Kama kila karatasi ya muhtasari katika kundi hili ni bure na inafanya kazi upande wa mteja: chuja safu moja kwa moja kwa kisanduku cha utafutaji, ruka kati ya sehemu kutoka kwenye jedwali la yaliyomo linalobaki juu, nakili kijisehemu chochote kwa mbofyo mmoja na chapisha ukurasa kuwa rejeo la mezani.
Jinsi ya kutumia Karatasi ya Muhtasari ya C++
- Fungua karatasi na upitie sehemu, kuanzia Basics, auto & references hadi Compilation & CMake.
- Tafuta neno kuu kama unique_ptr, ranges au concept ili kuchuja karatasi moja kwa moja.
- Ruka hadi Move semantics au Templates & concepts unapohitaji sintaksia ngumu zaidi ifafanuliwe.
- Bofya kijisehemu au ikoni yake ya kunakili ili kunakili msimbo wa C++ kwenye ubao wako wa kunakili.
- Tumia Chapisha kupata nakala ya karatasi ya rejeo kamili ya C++.