initialization
int a = 42.5;int a(42.5);int a{42.5};structured binding
auto [x, y, z] = f();reference
pass by value × pass by reference
l-value, r-value
const
you can't declare a non-const reference to a const variable
streams
>> operator reads until the next whitespacegetline()std::flush or std::endl can be used to flush\n (and std::ios::sync_with_stdio(false);) instead of std::endl if we want to use it repeatedlyofs.open("hello.txt", std::ios::app);std::ios::app … append flag>> operator on cin reads until the next whitespacegetline reads the whole linecontainers
iterators
(*it).x ~ it->x*(it+5) ~ it[5]classes
.h file (or .hpp?)this pointerusing … type aliasing (e.g. iterator)inheritance
B:A, C:A, D:B,C)templates
template <typename T> ~ template <class T>const methods
T* this, they can use only const T* thisconst T& at(size_t index) const;T& at(size_t index);const_cast … casts away constnessmutable … marks field as mutable even in const instancestemplated function
implicit × explicit instatiation
concepts
template <typename T>
concept Comparable = requires(const T a, const T b) {
{ a < b } -> std::convertible_to<bool>;
};
concepts (cont'd)
template <typename T> requires Comparable<T>template <Comparable T>recursion using variadic templates
template <Comparable T>
T min(const T& v) { return v; }
template <Comparable T, Comparable... Args>
T min(const T& v, const Args&... args) {
auto m = min(args...);
return v < m ? v : m;
}
compile-time code execution
constexpr … expression should be evaluated at compile timeconsteval … expression must be evaluated at compile timepassing predicates/functors
bool isVowel(char c) is passed as type bool(*)(char)operator()range
std::find(v.begin(), v.end(), x); for vector v, we can use std::ranges::find(v, x);view
std::ranges::views and std::ranges::to| operatorstd::ranges algorithms are eagerstd::ranges::views are lazyoperator overloading
special member functions
move semantics
Photo retake(0,0);retake = takePhoto();& reference, we would need to assign an address to the value firstPhoto selfie = takePhoto();upload(selfie);&& reference, we don't need to do soupload(takePhoto());std::move casts an lvalue to rvaluestd::optional<T> can hold std::nullopt or a value of type T
there is no std::optional<T&> :((
RAII … Resource Acquisition is Initialization