Tous les outils
Gratuit

Une référence C++ moderne consultable et imprimable — pointeurs intelligents, conteneurs, algorithmes, RAII, sémantique de déplacement, templates et concurrence. Gratuit.

Basics, auto & references

11
auto x = 42;
Type deduction (int here)
const auto& r = bigObject;
Cheap read-only reference
int& ref = x; ref = 5;
Reference: alias to a variable
constexpr int N = 10;
Compile-time constant
using Ids = std::vector<int>;
Type alias (modern typedef)
auto [key, value] = *map.begin();
Structured bindings (C++17)
if (auto it = m.find(k); it != m.end())
Init-statement inside if (C++17)
enum class Color { Red, Green };
Scoped enum (no implicit int)
nullptr
Typed null pointer (never NULL)
static_cast<int>(3.99)
Explicit checked-style cast
std::int64_t n = 0; // <cstdint>
Fixed-width integer types

Smart pointers

10
auto p = std::make_unique<Widget>(args);
Sole owner, freed on scope exit
auto s = std::make_shared<Widget>();
Ref-counted shared ownership
std::unique_ptr<Widget> q = std::move(p);
Transfer ownership (no copy)
std::weak_ptr<Widget> w = s;
Non-owning observer of shared
if (auto sp = w.lock()) sp->run();
Safely promote weak → shared
p.get()
Raw pointer view (no ownership)
p.reset();
Destroy the owned object early
s.use_count()
Current shared reference count
void observe(const Widget& w);
Pass & or * to non-owners
std::unique_ptr<T[]> a = std::make_unique<T[]>(n);
Owned dynamic array

Containers

12
std::vector<int> v{1, 2, 3};
Dynamic array (default choice)
v.push_back(4); v.emplace_back(args);
Append (emplace constructs)
v.reserve(1000);
Pre-allocate to avoid regrowth
std::map<std::string, int> m;
Sorted key→value tree
std::unordered_map<std::string, int> h;
Hash map (faster, unsorted)
m["hits"] += 1; m.at("hits");
[] inserts default; at() throws
if (m.contains(key)) ...
Membership test (C++20)
std::array<int, 3> a{1, 2, 3};
Fixed-size stack array
void f(std::span<const int> s);
Non-owning view of any array
std::set<int> s; std::unordered_set<int> u;
Unique-element containers
std::erase_if(v, [](int n) { return n < 0; });
Erase-remove in one call (C++20)
v.size(); v.empty(); v.clear();
Common capacity operations

Algorithms & ranges

12
std::ranges::sort(v);
Sort a whole container (C++20)
std::sort(v.begin(), v.end(), cmp);
Classic iterator-pair sort
auto it = std::ranges::find_if(v, pred);
First element matching pred
std::transform(v.begin(), v.end(), out, f);
Map each element into out
std::accumulate(v.begin(), v.end(), 0)
Sum / fold (<numeric>)
std::ranges::count_if(v, pred)
Count matching elements
v | std::views::filter(isEven)
Lazy filtered view (C++20)
| std::views::transform(square)
Chain lazy transformations
std::views::iota(0, 10)
Lazy range of ints 0..9
auto v2 = r | std::ranges::to<std::vector>();
Materialize a view (C++23)
std::ranges::max_element(v)
Iterator to the largest value
std::ranges::any_of(v, pred)
any_of / all_of / none_of

Strings & string_view

11
std::string s = "hi"; s += "!";
Owning, growable string
void f(std::string_view sv);
Non-owning read-only view
if (s.find("x") != std::string::npos)
Substring search
s.substr(1, 3)
Slice (pos, length)
s.starts_with("http"); s.ends_with(".h");
Prefix / suffix tests (C++20)
s.contains("needle")
Substring test (C++23)
std::to_string(42)
Number → string
int n = std::stoi("42");
String → int (stod, stol...)
std::format("{}: {}", key, count)
Type-safe formatting (C++20)
std::getline(std::cin, line);
Read a whole input line
R"(C:\path\no "escapes")"
Raw string literal

Classes & RAII

11
struct Point { int x = 0; int y = 0; };
struct: public by default
Widget() : size_{0}, name_{"w"} {}
Member initializer list
~Widget() { close(handle_); }
Destructor releases resources
ctor, dtor, copy ctor/=, move ctor/=
Rule of five (define all or none)
Widget(const Widget&) = delete;
Forbid copying
Widget(Widget&&) noexcept = default;
Opt into generated move
explicit Widget(int size);
Block implicit conversions
int size() const { return size_; }
const member: no mutation
virtual void draw(); / void draw() override;
Polymorphism + override check
virtual ~Base() = default;
Virtual dtor for base classes
[[nodiscard]] bool ok() const;
Warn when return is ignored

Move semantics

9
auto b = std::move(a);
Cast to rvalue: steal resources
Widget(Widget&& o) noexcept;
Move constructor signature
return result;
Return by value: NRVO or move
void set(std::string s) { s_ = std::move(s); }
Sink param: by value + move
v.push_back(std::move(str));
Move into a container
auto old = std::exchange(ptr_, nullptr);
Take value, reset the source
std::swap(a, b);
Exchange two values cheaply
// moved-from: valid but unspecified
Only assign/destroy after move
template <class T> void f(T&& x) { g(std::forward<T>(x)); }
Perfect forwarding

Templates & concepts

10
template <typename T> T maxOf(T a, T b);
Function template
template <std::integral T> T half(T n);
Constrain with a concept (C++20)
template <class T> concept Number = std::is_arithmetic_v<T>;
Define a custom concept
void print(const auto& x);
Abbreviated template (C++20)
if constexpr (std::is_integral_v<T>)
Compile-time branch
std::pair p{1, 2.5};
CTAD: deduce class template args
template <typename... Args> void log(Args&&... args);
Variadic template
(args + ...)
Fold expression over a pack
template <class T> requires Number<T> T sq(T x);
requires clause
template <> struct Hash<Key> { ... };
Explicit specialization

Lambdas & std::function

10
auto twice = [](int x) { return x * 2; };
Basic lambda
[=] captures copies; [&] captures refs
Default capture modes
[x, &total](int n) { total += x * n; }
Mixed explicit captures
[this] { return counter_; }
Capture the enclosing object
[p = std::move(ptr)] { p->run(); }
Init-capture (move into lambda)
[n = 0]() mutable { return ++n; }
mutable: modify captured copies
[](auto a, auto b) { return a < b; }
Generic lambda
[](int x) -> double { return x / 2.0; }
Explicit return type
std::function<int(int)> cb = twice;
Type-erased callable holder
std::ranges::sort(v, {}, &User::age);
Projection instead of a lambda

Error handling

11
std::optional<int> parse(std::string_view s);
Maybe-a-value return type
opt.value_or(0)
Unwrap with a fallback
if (opt) use(*opt);
Test then dereference
std::expected<Data, Error> load();
Value-or-error return (C++23)
res.and_then(step).transform(format)
Monadic chaining (C++23)
throw std::runtime_error("bad config");
Throw a standard exception
catch (const std::exception& e) { e.what(); }
Catch by const reference
void close() noexcept;
Promise not to throw
assert(ptr != nullptr);
Debug-only invariant check
static_assert(sizeof(int) == 4);
Compile-time assertion
std::variant<int, Err> v; std::visit(fn, v);
Closed sum type + visitor

Concurrency

10
std::jthread t(work);
Auto-joining thread (C++20)
std::thread t(work); t.join();
Classic thread (must join)
std::mutex m; std::lock_guard lock(m);
Scoped lock (RAII)
std::scoped_lock lock(m1, m2);
Lock several without deadlock
std::unique_lock lk(m); cv.wait(lk, ready);
Condition variable wait
std::atomic<int> hits{0}; ++hits;
Lock-free counter
auto f = std::async(std::launch::async, fetch);
Run async, get a future
auto result = f.get();
Block until the result is ready
std::this_thread::sleep_for(100ms);
Sleep (std::chrono_literals)
thread_local int cache = 0;
One instance per thread

Compilation & CMake

11
g++ -std=c++23 -Wall -Wextra -O2 main.cpp -o app
Typical release compile
clang++ -std=c++20 main.cpp -o app
Same flags work with clang
-g -O0
Debug build (symbols, no opt)
-fsanitize=address,undefined
Catch memory/UB bugs at runtime
-Iinclude -Llib -lfoo
Header path, lib path, link lib
-DNDEBUG
Strip assert() in release
cmake_minimum_required(VERSION 3.20)
CMakeLists.txt first line
add_executable(app main.cpp)
Declare the binary target
target_compile_features(app PRIVATE cxx_std_23)
Require a C++ standard
cmake -B build && cmake --build build
Configure then build
cmake --build build -j 8
Parallel build

Aucune entrée ne correspond à « :q ».


À propos de Aide-mémoire C++

Cet aide-mémoire C++ rassemble le C++ moderne en une seule référence consultable : bases avec auto et références, pointeurs intelligents, conteneurs, algorithmes et ranges, chaînes et string_view, classes et RAII, sémantique de déplacement, templates et concepts, lambdas et std::function, gestion des erreurs, concurrence, et compilation avec CMake.

Il vise le C++ que les gens écrivent réellement aujourd'hui — unique_ptr et shared_ptr au lieu de new et delete bruts, algorithmes sur ranges, liaisons structurées, concepts sur les templates, std::thread et std::mutex — tout en explicitant les fondamentaux comme la règle des cinq et RAII.

Comme chaque aide-mémoire de ce groupe, il est gratuit et côté client : filtrez les lignes en direct avec la barre de recherche, sautez entre les sections depuis le sommaire épinglé, copiez n'importe quel extrait d'un clic et imprimez la page comme référence de bureau.

Comment utiliser Aide-mémoire C++

  1. Ouvrez la fiche et passez en revue les sections, des Bases, auto et références à la Compilation et CMake.
  2. Recherchez un mot-clé comme unique_ptr, ranges ou concept pour filtrer la fiche en direct.
  3. Sautez à la Sémantique de déplacement ou aux Templates et concepts quand vous avez besoin que la syntaxe la plus ardue soit explicitée.
  4. Cliquez sur un extrait ou son icône de copie pour copier le code C++ dans votre presse-papiers.
  5. Utilisez Imprimer pour une copie papier de la référence C++ complète.

Questions fréquentes

Douze sections : bases avec auto et références, pointeurs intelligents, conteneurs, algorithmes et ranges, chaînes et string_view, classes et RAII, sémantique de déplacement, templates et concepts, lambdas et std::function, gestion des erreurs, concurrence, et compilation avec CMake.

Moderne. Il commence par les pointeurs intelligents, RAII, la sémantique de déplacement, les liaisons structurées, les ranges et les concepts plutôt que la gestion manuelle de la mémoire.

Oui. Les sections conteneurs et algorithmes listent vector, map, unordered_map, set, deque et les algorithmes courants — sort, find, transform, accumulate — avec leurs formes basées sur les ranges.

Oui. Cliquez sur le code de n'importe quelle ligne ou son icône de copie et il est copié immédiatement.

Oui, elle est entièrement gratuite et s'exécute dans votre navigateur sans connexion.


Recherches populaires
c++ cheat sheet référence c++ moderne pointeurs intelligents c++ conteneurs stl cheat sheet liste des algorithmes c++ sémantique de déplacement c++ templates et concepts c++
Besoin d'aide ?
Un problème avec cet outil ? Signalez-le à notre équipe.
Signaler un problème

Ajoutez cet outil gratuit à votre propre site web — copiez-collez le code ci-dessous.