All tools
Free

A searchable, printable modern C++ reference — smart pointers, containers, algorithms, RAII, move semantics, templates and concurrency. Free.

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

No entry matches “:q”.


About C++ Cheat Sheet

This C++ cheat sheet gathers modern C++ into one searchable reference: basics with auto and references, smart pointers, containers, algorithms and ranges, strings and string_view, classes and RAII, move semantics, templates and concepts, lambdas and std::function, error handling, concurrency, and compilation with 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.

Like every cheat sheet in this group it is free and client-side: filter rows live with the search box, jump between sections from the sticky table of contents, copy any snippet with one click and print the page as a desk reference.

How to use C++ Cheat Sheet

  1. Open the sheet and review the sections, from Basics, auto & references to Compilation & CMake.
  2. Search for a keyword such as unique_ptr, ranges or concept to filter the sheet live.
  3. Jump to Move semantics or Templates & concepts when you need the harder syntax spelled out.
  4. Click a snippet or its copy icon to copy the C++ code to your clipboard.
  5. Use Print for a paper copy of the full C++ reference.

Frequently asked questions

Twelve sections: basics with auto and references, smart pointers, containers, algorithms and ranges, strings and string_view, classes and RAII, move semantics, templates and concepts, lambdas and std::function, error handling, concurrency, and compilation with CMake.

Modern. It leads with smart pointers, RAII, move semantics, structured bindings, ranges and concepts rather than manual memory management.

Yes. The containers and algorithms sections list vector, map, unordered_map, set, deque and the common algorithms — sort, find, transform, accumulate — with their range-based forms.

Yes. Click the code on any row or its copy icon and it is copied immediately.

Yes, it is completely free and runs in your browser with no login.


Popular searches
c++ cheat sheet modern c++ reference c++ smart pointers stl containers cheat sheet c++ algorithms list c++ move semantics c++ templates and concepts
Need help?
Found an issue with this tool? Let our team know.
Report an issue

Add this free tool to your own website — copy and paste the code below.