C++ notes

A random collection of C++ domain notes

Compilation Process

Inspired by: https://www.youtube.com/watch?v=dOfucXtyEsU

Broken down into a few stages

  • Pre-processing - Prepares source code for compilation

    • Macro expansion: handles #define
    • Headers: replace #include with actual content of the file
      • When you do #include <> , preprocessor looks for headers in standard system directories like /usr/include or /usr/local/include (when you download c++ with apt install build-essentials for example, it places all those header files there)
      • When you do #include "" , compiler looks for headers in the current directory (same directory as the source file, not where the compiler is called)
    • Handles condition compilation of if, ifdef, ifndef
    • Remove comments (lol)
    • Outputs a “Translation Unit” per source file (per .cpp file), with file extension .i
  • Compiling - Translates source code into assembly

    • Syntax and semantical analysis: source code is parsed here, if syntaxtically incorrect then error will be thrown at this stage. logical errors such as type mismatch are also checked here
    • Roughly goes like: Tokenizing → Parsing into AST → Semantic Analysis → IR generation → Optimization → Translates final IR into assembly
    • Outputs a .s or .asm assembly code file
    • An assembly file contains a few key sections (looks like the following)
    .file "example.cpp"    # Directive: source file name
    
        .globl my_num          # Directive: make 'my_num' global
        .data                  # Section: initialized data starts here
        .align 4
    my_num:                    # Label: variable location
        .long 5                # Data: the 32-bit integer '5'
    
        .text                  # Section: executable code starts here
        .globl main            # Directive: make 'main' global
    main:                      # Label: function start
        movl my_num(%rip), %eax # Instruction: move 'my_num' into the 'eax' register
        ret                    # Instruction: return the value in 'eax'
  • Assembling - Translates the assembly code into machine code

    • Exact byte offsets need to be calculated for jump and branches
    • Create the symbol table: Records all functions and global variables defined in the file (exports), and all the external functions it needs (imports)
    • Generates relocation records: When there is a call to an external function, the assembler puts dummy 0s into the machine code (for the linker to come and patch later)
    • Divides the program into .text (code), .data (initialized variables), and .bss (uninitialized variables)
    • Outputs a .o object file, each translation unit gets converted into its own object file
    • note: gcc uses the gnu assembler meanwhile clant uses the LLVM integrated assembler
  • Linking - Links object files together to generate an executable

    • Scans symbol table for imports and exports, and tries to resolve all of them (throws if cannot or multiple definition)
    • Merge sections of code, initialized variables, and uninitialized variables together. Assigns a final virtual memory address to all lines of code and global variables
    • Patch relocation records with appropriate jumps to functions
    • Handling libraries:
      • Static linking (library is in a .a or .lib file): Copies the library code into the final executable
      • Dynamic linking (library is in a .so or .dll file): Loads the library code on the fly, smaller executable but user must have the library file
      • Obviously for header/source level libraries, they are just compiled as regular code
      • To create your own static library, compile source code into object code with -c , then archive the object files with the archiver tool ar
      • For your own shared/dynamic library, compile with -c and -fPIC for position independent code (machine code that do not rely on specific memory address) and then compile the .o files with -shared into an .so file

Note that you can use -E flag to get *.i files (tell compiler to stop immediately after preprocessing, likewise -S for assembly, -c for object code

All this should make it clear why you want separate .hpp for declaration and .cpp for source code definitions. .cpp are treated as separate translation units. and #includes are simply just replacing the code with the file content. it is preferable to only include the declarations, so that when you need to recompile, you don’t need to recompile the source code of those functions again.

Furthermore, if you are distributing proprietary code, you can just distribute the public API headers AND the .a/.lib or .so/.dll library files since they are machine code.

C++ Version history and major changes

C++11

  • Move semantics, RValue references
  • Smart pointers
  • Type inference
  • Ranges, Concurrency, Labmdas
  • constexpr, nullptr, override, final

C++14

  • Variable templates

C++17

  • Structured Bindings
  • Vocabulary types: std::optional std::any std::variant
  • CTAD (class template argument deduction)
  • Fold expressions

C++20

  • Concepts
  • Modules??
  • Coroutines
  • Ranges

Good to knows: string_view (C++17), span (C++20)

Basic concepts

  • Type system
    • void, nullptr
    • Conversion rules
    • Integral and floating type arithmetic
      • Two’s complement
    • auto, decltype
  • Operators, precedence
  • Functions: Lambdas
  • Pointers, references, const properties
  • Contexpr
  • sizeof, alignof, alignas
    • **attribute**((packed))

Integral and floating type arithmetic

Some behavior stuff

  • Signed integer overflow is undefined behavior
  • Unsigned integer overflow is defined
  • Division by zero is undefined

Type promotions

  • Smaller integer types are promoted to int

Pointer, references, const properties

Trivia

  • Const objects cannot be moved from, compiler will just make a copy silently

Functions in C++

  • Defined by function name + parameter types + random qualifiers
    • Note that return type does not uniquely change this
    • Qualifiers such as const, volatile, & and &&

All function qualifiers:

  • const , volatile
  • static
  • inline
  • noexcept
  • constexpr and consteval

Within a class

  • & and && indicates whether the function can be called on an lvalue or rvalue object
  • virtual
  • explicit
  • override, final
  • friend : can be used on a function too

OOP, Classes in C++

  • RAII Idiom
  • Basic Classes
    • Access specifiers: public , protected , private
    • Basic keywords: this, static, mutable, friend, explicit
    • Constructor, Deconstructor
      • Copy/Move
      • Default behavior, deletion behavior
  • Polymorphism
    • Keywords: virtual , override, final
    • VTable
  • Bonus trivias
    • Class properties
    • Slicing
    • Functors

Class concepts

  • A C Structure (struct) is a collection of variables under a single name
    • In C, structs can only hold function pointers, not functions
  • A C++ class extends the concept of a struct to hold functions as members
    • In C++, struct and classes are the same thing (except default access)
    • In practice, use struct for passive objects and classes for active

RAII (Resource Acquisition is Initialization) Idiom

  • Use ctor and dtor to create and destroy resources
  • The resource is automatically released when object gets out of scope
class B;
class A : B {
} // class A extends B (A is a derived class of B
// B is base/parent class, A is child/derived

Access specifiers: there is public protected private visibility

public: Can be accessed outside the class

protected: Only within the class and derived classes

private: Only within the class

class B;
class A : public B {}; // B public -> A public, B protected -> A protected
class A : protected B{}; // B public -> A protected, B protected -> A protected
class A : private B{}; // B public -> A private, B protected -> A private
// classes default to private if you don't write anything
// structs default to public

protected and private

Constructors and Destructors

Every class has always either an implicit, explicit, or deleted default constructor

  • Implicit: auto generated
  • Explicit: user defined
  • Deleted: if user defined a non-default constructor, manually deleted it, or it has to generate a reference or const, or if any members don’t have default constructor/destructor
struct A{
	A () {}; // explicit user defined default constructor
	A(int) {}; // user defined non-default constructor
	A() = delete; // manually deleted default constructor
};

Constructor member-initializer list: Something like A(const char* str1) : str{str1} {}, must follow the order of declaration of members.

  • Allows you to initializes an object’s base classes and data members before the constructor body executes, hence const and reference data members can be initialized this way

Not to be confused with “Uniform initialization”, which is used when initializing an object.

  • Minimizes redundant type names
  • C++11, and solves the most vexing parse problem
struct Point {
	int x, y;
	// this doesn't have to be a member initializer list to
	// use uniform initialization
	Point(int x1, int y1) : x(x1), y(y1) {}
};

Point c = add(Point(1, 2), Point(3, 4));
auto c = add({1, 2}, {3, 4}); // uniform initialization, type-deduced

To summarize all types of initialization

  • Brace == list initialization
  • Moves use the copy-initialization syntax, but instead of expr you do std::move(expr); Function overloads select the move constructor
A a;          // default-initialization
A a();        // function declaration: most vexing parse, not initialization
A a{};        // direct-list-initialization
A a(expr);    // direct-initialization
A a = expr;   // copy-initialization
A a = {expr}; // copy-list-initialization

Random tidbit Most Vexing Parse

  • C++ does not allow a non-static data member to be initialized with parentheses inside the class definition
  • C++ also (inherited from C) prefers to interpret ambiguous cases as declaration over initialization
struct A {
	A(int) {}
};
struct B {
	A a(1); // compile error (not the most vexing parse)
	A a{2}; // ok, brace initializer syntax
	A a = A(1); // ok, equals initializer syntax
	B (A a) {}; // constructor
};
B b (A()); // most vexing parse
B b(); // also most vexing parse
  • B b (A ()); is interpreted as a function b that returns struct B, which takes in a function pointer that returns A
  • B b(); is interpreted as a function that returns struct B with no parameters
  • Can occur at any scope

Constructors are called in the order from top base class to most derived class

struct A {
	A() { cout << "A"; };
};
struct B1 : A {} // will call A() implicitly
struct B2 : A { 
	// constructor member-initializer list can also be used for base objects
	B2() : A() {} // will call "A()" explicitly
};

A destructor is called when an object goes out of scope or whenever delete/delete[] is applied to a pointer of that object. Expressed with ~T() syntax. A destructor can not take in arguments. Are called in reverse order from most derived to top base.

  • A destructor must be public for an object was created on stack, or it wouldn’t compile

Keywords in the context of classes

  • Explicit: specifies an operator or constructor does not allow copy-initalization
  • this: To access the object’s own address within class scope
  • static: In the context of classes, it declares member field or methods that are not bound to class instances, but instead shared by all objects of that class
    • Upon first calling a static something, a bool is usually created to check if it has been created yet, if so, then refer to what has already been created
  • const: member functions marked with const are not allowed to change the object’s logical state (a vector’s element may be changed, but not the vector itself, standard const correctness stuff)
  • mutable: Marks a data member as part of physical state, a const class instance’s mutable data members can still be modified
  • using: used declare a type alias, can be also used to change the inheritance attribute of data members and functions
  • friend: friend class can access the private and protected members of the class in which it is declared as a friend. Friendliness is not inherited and not transitive and not symmetric
    • class A {friend class B} means class B can access A, not reverse
  • delete: marks a member function as deleted and any use results in a compiler error

Rule of 0/3/5

In C++, if you define any of these (pre c++11 no moves, hence only 3) you should specify behavior for all of them (whether its custom, or default, or delete)

~A() // destructor
A(A& a) // copy constructor
A(A&& a) // move constructor
A& operator=(A& a); // copy assignment operator
A& operator=(A&& a); // move assignment operator

Polymorphism

Polymorphism: Invoking different behavior with a common interface based on the object’s underlying concrete type

Keywords

  • virtual : declears a function’s binding should be decided at runtime, rather than compile
  • override : on a derived class, ensures that a function definition is overriding a base class’s virtual function
  • final : prevents a derived class from overriding this function any further

A pure virtual method is a function that must be implemented in derived class

Declared with: virtual void f() = 0;

The virtual table is a lookup table of functions used to resolve runtime bindings.

Compiler adds a hidden pointer to classes that require runtime polymorphism, sizeof considers the vtable pointer.

Vtable contains entries for all virtual functions that can be called, and points to the most derived function pointer.

Behavior of virtual, pass by reference/pointer is ok, pass by value performs a cast

This is called slicing

struct A {
virtual void f() { cout << "A"; }
};
struct B : A {
void f() override { cout << "B"; }
};
void f(A& a) { a.f(); } // ok, print "B"
void g(A* a) { a->f(); } // ok, print "B"
void h(A a) { a.f(); } // does not work with pass-by value!! print "A"
B b;
f(b); // print "B"
g(&b); // print "B"
h(b); // print "A" (cast to A)

Run-Time Type Information (RTTI) are mechanisms that allows a C++ program to identify the actual type of an object while the program is running

  • dynamic_cast : performs a cast and returns the pointer, returns null if cannot cast
  • typeid : returns a type_info object

Property of classes: https://en.cppreference.com/cpp/language/classes#Standard-layout_class

  • Standard layout: a class with same memory as equivalent C struct or union
    • No virtual function, non-static data members
  • Trivial class: one that is trivially copyable
    • No virtual function and user provided copy/move/default constructor destructor and copy/move assignment operators
  • Aggregate: support aggregate initialization
    • Meaning you initialize members directly (unlike vector or something like that where you’re populating an array)

Slicing:

The memory layout of derived classes is like

  • [VPTR | Base class members] [VPTR | Derived class members]

Lets say you have base class A and derived class B

If you try to copy a B object into an A, it slices off the extras

Templates, Metaprogramming

  • Function and class templates
    • Default values, overloading, specialization, auto types
  • Type traits

Advanced concepts

  • Constructor Template Automatic Deduction (CTAD)
  • SFINAE, Concepts
  • Variadic templates
    • Parameter pack
    • Folding expressions

Template

Templates is a form of generics programming. Can represent a family of functions, classes, or variables (C++14 only).

Templates are instantiated during compile time, during which

  • substitute the template
  • evaluate SFINAE rules
  • performs deep semantic check on the newly generated code
  • writes a new, hidden, concrete class/function/variable into AST

Templates can be implicitly or explicitly instantiated

Template parameters are what can be passed into the template

  • Can be a type template parameter, such as typename, class, C++20 concepts, another template, etc
  • Or a Non-Type Template Parameter NTTP), in which case it is more like compile-type values

Example parameter types

  • Generic typename
  • Integral type
  • enum, enum class
  • nullptr_t (C++14)
  • auto (C++17)
  • class literals and concepts (C++20
  • floating point type (C++20)
// Regular function template
template <typename T>
T add(T a, T b) { return a+b; }

// Non-Type Template Parameter (NTTP)
template <int A, int B>
int add() { return A+B; }

// default values C++11
tempalte <int A=3, int B=2>
int add() { return A+B; }
add(); // returns 5
add<1>(); // returns 1+2=3, the first one is substituted
add<1, 1>(); // returns 2

// default value may be void
// usecase: function only exists if it is ever called (smaller binary)
template<typename= void>
int f() {}

// you can do this btw (use previous values to initialize)
template<typename T, int S= sizeof(T)>

Template specialization refers providing different implementations for specific template argument combinations

// terrible for floats
template<typename T>
bool compare(T a, T b) {
	return a < b;
}

template<>
bool compare<float>(float a, float b) {
	return std::abs(a - b) < std::numeric_limits<float>::epsilon; 
}
/*
generally you would just rather write a bool compare(float float) function
this is because regular function overload resolution rules + function template
+ base templates makes things kinda confusing

Therefore: Don't fully specialize function templates
*/

Some shenanigans with template resolving

template<typename T>
T add(T a, T b) { return a + b; }

template<typename T>
int add(int a, int b) { return a + b + 1; }

add(1,2); // returns 3
add<int>(1,2) // returns 4
/*
Something about how when you do add(1,2), you cannot deduce what typename T
is for the second function, thus we must pick the first one...
*/

template<typename T>
T add(T a, T b, T c) { return a + b; }

template<typename T>
int add(int a, int b, T c) { return a + b + 1; }
add(1,2,3); // Compilation error because two equally valid cases, ambiguous

// template specializations applies to templates already visible
template <typename T>void print(T) { fmt::print("Generic"); };
template <typename T>void print(T*) { fmt::print("Overload"); };
template<>void print(double*) { fmt::print("Specialization"); };
double d = 1.5;
print(&d); // prints specizliation

template <typename T>void print(T) { fmt::print("Generic"); };
template<>void print(double*) { fmt::print("Specialization"); };
template <typename T>void print(T*) { fmt::print("Overload"); };

double d = 1.5;
print(&d); // prints overload

C++11 adds variadic templates

... Can be used to defined parameter packs in templates

template <typename... Ts>
void f(Ts... args) {
    // ...
}
// if you call f(1, 2.5, "hello");
// then conceptually (note that this is within compiler so Ts isnt a tuple)
Ts   = int, double, const char*
args = 1,   2.5,    "hello"

People do not expand parameter packs with indexing, it is unpacked with ... on the other side.

... unpacks things as T0, T1, T2, T3, etc

template <typename... Args>
void wrapper(Args... args) {
		func(args);
}

/*
wrapper(1, 2.5, 3, 4.5)
Args... becomes `int, double, int, double`
args... becomes `1, 2.5, 3, 4.5`
so you end up calling func(1, 2.5, 3, 4.5)

you can do more complicated things such as 
*/

template <typename... Args>
void f(Args&&... args) {
    g(std::forward<Args>(args)...);
}
// Note that Args is the type pack, hence you pass to the forward<>
// and args is the value pack
// this gets unpacked to
g(
    std::forward<Arg1>(arg1),
    std::forward<Arg2>(arg2),
    std::forward<Arg3>(arg3)
);

C++17 extends elipses to fold expressions, pack expansion only allows for a list of arguments separated by commas, but fold expression expands that to other operators

C++14 adds template variable, not much fun there, a static value for a template

template<typename T>
constexpr T pi{ 3.1415926535897932385 }; // variable template
template<typename T>
T circular_area(T r) {
return pi<T> * r * r; // pi<T> is a variable template instantiation
}
circular_area(3.3f); // float
circular_area(3.3); // double

SFINAE and Concepts

SFINAE (Substitution Failure Is Not An Error) is essentially the compiler only compiling a template if it makes sense, and doesn’t crash in cases where it does not

The benefit is that it specializes over a category of types, over template specialization which is just one at a time.

#include <type_traits>

/*
std::is_integral_v<T> evaluates if the type is an integral
evaluates to true if yes, falsei if no

enable_if_t<Condition, Type>
if condition is true, transforms into an int, otherwise evaluates to nothing

we just assign 0 to it but it doenst matter

Yes this is messy, but SFINAE was unintended
*/
template <typename T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
void print_value(T val) {
    std::cout << "Integral: " << val << '\n';
}

template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
void print_value(T val) {
    std::cout << "Float: " << val << '\n';
}

print_value(42);   // Calls Candidate 1
print_value(3.14); // Calls Candidate 2

Concepts are introduced in C++20 to solve allow constraints on template type parameters

You can invoke it in many ways

#include <concepts>

// implicit template with auto
void printEven(std::integral auto number) {
    if (number % 2 == 0) {
        std::cout << number << '\n';
    }
}

// with the requires clause prefix
template <typename T>
requires std::integral<T>
void printEven(T number) { ... }

// with the requires clause suffix
template <typename T>
void printEven(T number) requires std::integral<T> { ... }

// template constraint way
template <std::integral T>
void printEven(T number) { ... }

/*
Only difference between suffix and prefix is that
suffix can act on the function parameters

the following would crash if it was prefix
*/
template <typename T>
void printEven(T number) requires (sizeof(number) > 2) { ... }

/*
Syntax for the requires clause:
requires (boolean expression)

You can also use requires in an expression
requires (T x) { x.doSomething(); }
this requires generates a boolean for whether the following code will compile

*/

// thus this can get ugly too, the first require is the clause, 2nd is exp
template <typename T>
void printEven(T number) requires requires { number % 2; } { 
    // This function is only valid for types where "number % 2" is valid syntax
}

You can define your own concepts

template <typename T>
concept Integral = std::is_integral_v<T>;

template <typename T>
concept Addable = requires(T a, T b) {
    // 1. It must support the '+' operator
    a + b; 
    
    // 2. The result of 'a + b' must be exactly the same type as T
    { a + b } -> std::same_as<T>; 
};

Here are a list of useful concepts (idk if they’re actually right, what chatgpt says

CRTP - Curiously Recurring Template Pattern

A C++ pattern where a derived class passes itself as a template parameter to its base class

It is used to achieve compile-time polymorphism

template <class Derived>
class Base {
public:
	void interface() {
		// transforms into Base<Foo>::implementation() at compile time
		static_cast<Derived *>(this)->implementation();
	}
};

class Foo : public Base<Foo> {
public:
	void implementation() {
	}
};

Here is the comparison with regular runtime polymorphism

class Base {
public:
	virtual void implementation() = 0;
};
class Foo : public Base {
	void implementation() override {
	}
};

// Calling through Base* requires virtual dispatch
Foo f;
Base* p = &f;
p->implementation();  // vtable dispatch

Foo foo;
Base<Foo>* p = &foo;
p->implementation(); // compile time handling

Another use of this is in functions, essentially use it to type the parameters to generate differnet run functions.

void run(Base& obj) {
    obj.implementation();  // virtual dispatch
}

template <typename T>
void run(Base<T>& obj) {
    obj.implementation();
}

Foo foo;
Bar bar;

Note that CRTPed classes won’t let you do things like std::vector<Base*> objects; since Base now requires a template type, and it won’t let you store a generic in a vector for example.

In C++ 23, “deducing this” was a feature, formally known as explicit object parameter, lets a member function expose the object *this as an actual function parameter whose type can be deduced. This gives you compile time access to an object’s constness and value category

struct Foo {
    template <typename Self>
    void f(this Self&& self) {
        // Self is deduced from the object used to call f()
    }
};
Foo f;
const Foo cf;

f.f();             // Self ≈ Foo&
cf.f();            // Self ≈ const Foo&
std::move(f).f();  // Self ≈ Foo

This avoids duplicating const/non-const overloads, but also makes CRTP a lot cleaner

// C++ 20 CRTP
template <typename Derived>
struct Base {
    void interface() {
        static_cast<Derived*>(this)->implementation();
    }
};

struct Foo : Base<Foo> {
    void implementation() {
        std::cout << "Foo\n";
    }
};
// C++ 23 CRTP
struct Base {
    template <typename Self>
    void interface(this Self&& self) {
        self.implementation();
    }
};

struct Foo : Base {
    void implementation() {
        std::cout << "Foo\n";
    }
};
// you no longer need a disgusting static_cast along with template on Base

Deducing this also makes recursive lambdas much cleaner

Compilation, Translation Unit, and Linkage

  • Scope/Accessibility: Local/Block, Global/File/Namespace
    • Variable shadowing
    • Storage duration
  • Linkage: None, Internal, External
  • Symbol, the symbol table, symbol visibility
    • Storage duration/Lifetime of variables
    • One Definition Rule
  • Overload resolution

Basics

A translation unit is a unit of compilation in C++, consists of content from a single source file

g++ -c main.cpp foo.cpp Each file passed to compiler gets its own translation unit (for pre-processing which folds in all the includes)

Scope: where a variable/function/object can be accessed

  • Local/Block Scope: Entities that are declared inside a function or a block are called local variables. Their memory address is not valid outside their scope
  • Global Scope / File Scope / Namespace Scope: Entities that are defined outside all functions. Holds a single memory location throughout the life-time of the program

Symbols: named items in a program which can refer to variables, functions, classes

Linkage: whether a symbol can be referred to in other scopes/translation units

  • No linkage: Symbols in the local scope and not visible
  • Internal linkage: Symbols accessible within a translation unit, not outside of it
  • External linkage: Symbols accessible through the whole program

Symbol visibility: whether the compiled symbol exposed outside the object file or shared library

  • Default: visible and can be linked against
  • Hidden: not visible, note that multiple libraries that export symbols with the same name could potentially cause undefined behavior at runtime
  • Only externally linked symbols can be visible

Storage Duration

  • Automatic: Code block start and end
  • Static: Either program start or first time calling, destruction at program exit
  • Dynamic: Memory allocation and deallocation
  • Thread: thread start and end

static keyword

  • Local variables:
    • Allocated when program begins, initialized at first function call, deallocated when program ends
  • Global variables:
    • Normally, without static variables, global variables are already “static”
    • static on global variables or functions affect linkage, it indicates internal linkage, so there would be no conflict with other translation units

Anonymous Namespace

  • Within an anonymous namespace, you have internal linkage
  • Essentially the same as declaring everything static, but captured in a scope

extern Keyword indicates existence of global variables or functions in another translation unit

  • can lead to ODR without it

const Variables have internal linkage at global scope

What is ODR? One Definition Rule?

In a single translation unit, templates functions class cannot have more than one definition, otherwise compilation error.

Across multiple translation units, the definition can exist in many places, but they must be the same. Otherwise it is undefined behaviour.

Move Semantics, Universal References

  • LValue vs RValue, RValue references
  • Move vs copy semantics
  • Universal references and perfect forwarding

Move semantics

  • Copy semantics duplicate the resources, move semantics transfers the ownership of resources from one object to another
  • In C++, every expression is either an lvalue or rvalue
    • Expressions are literals, variables/identifiers, operations, function calls, or even assignments (a=b=5 has b=5 as an rvalue expression)
  • lvalue: occupies an identifiable location in memory
  • rvalue: does not occupy a location in memory
  • You would expect only lvalue can be referenced X& , but C++11 introduces move semantics and introduced rvalue reference X&&
class X {
public:
		X(); // default constructor
		X(const X& obj); // copy constructor
		X(X&& obj); // move constructor
		X& operator=(const X& obj); // copy assign operator
		X& operator=(X&& obj); // move assign operator
		∼X(); // destructor
};
  • You can use std::move to cast an lvalue to an rvalue (basically relinquish ownership of the data), hence this is called move semantics

Universal References and Perfect Forwarding: std::forward<T>()

std::forward<T> casts a variable to an rvalue if and only if it was originally passed to the function as an rvalue. This is because when you pass an rvalue into a function, it implicitly becomes an lvalue (because now it has a name)

// the string&& indicates that this function ONLY accepts rvalue
void process(std::string&& text) {
		// text is lvalue here
}

Underneath the hood, std::forward<T> is simply using reference collapsing rule (only rvalue + rvalue is rvalue, everything else is collapsed to lvalue). This collapsing thing is called the universal reference (aka forwarding reference).

template <typename T>
constexpr T&& forward(std::remove_reference_t<T>& arg) noexcept {
		return static_cast<T&&>(arg);
}
/*
When you pass in a lvalue type like int&
typename T = int&
(int&) && is collapsed to int&

When you pass in a rvalue type like int&&
typenane T = int&&
(int&&) && is collpased to int&&
*/

// This is an RVALUE reference. 'int' is concrete, not deduced
void takeRvalue(int&& x) {} .

// This is a FORWARDING reference. 'T' is deduced.
template <typename T>
void takeUniversal(T&& x) {} 

TODO: add some example cases where you want to use std::forward

Advanced random stuff

  • Smart Pointers
  • Type deduction
  • std::initializer_list
  • Coroutines
  • Ranges
  • string_view
  • Designated initializers
  • const correctness
  • iterator invalidation rules in STL
  • C++ object layouts
  • Return value optimization

Smart Pointers

Pointer types with additional functionality

  • std::unique_ptr
  • std::shared_ptr
  • std::weak_ptr

If a smart pointer goes out of scope, the memory is deallocated accordingly

Other Practical C++ Knowledge

STL Container Implementations

  • Basic data structure, and their underlying mechanics
  • Iterators
  • Allocators

STL Algorithm Library

  • Sorting: sort, stable_sort
  • Search: find, find_if
  • Binary searching: lower_bound , upper_bound , binary_search

Important String/Parsing knowledge

For modern C++, prefer using

For getting text inputs

  • std::cin >> x; for tokens
  • std::getline(in, line); for getting entire lines

For getting raw bytes

// get file bytes into buffer
std::ifstream file("data.bin", std::ios::binary);

std::array<char, 4096> buf;
file.read(buf.data(), buf.size());
auto n = file.gcount();

// to get cin bytes into buffer
std::cin.read(reinterpret_cast<char*>(buf.data()), buf.size());

// create a span over buffer
std::span<std::byte> bytes(buf.data(), n);
  • std::string_view for strings
  • std::span for bytes

To process string_view, here are some important functions

Optimization Techniques

  • Function inlining
  • Cache warming
  • Branch predict reduction
  • Short circuiting
  • Loop unrolling

More compile time goodies

auto: Deduces the type of a value

  • Strips reference and const of the type of value

decltype: Deduces the type of an expression

  • Keeps reference or constness

inline : investigate?? seems to be weird

int& getRef() { return global_val; }

auto val1 = getRef();           // val1 is int (creates a copy)
decltype(auto) val2 = getRef(); // val2 is int& (creates a reference)

// you don't have to do this with decltype(auto) which is c++14
decltype(getRef()) val2 = getRef();

Linkage and Function Call Resolution

There are two concepts in C++ commonly conflated.

  1. Function resolution: Occurs within a single translation unit. Determines which function declaration a call refers to.
  2. Linking: Maps a declared function to a function definition (done by symbols)

During function resolution, the following are performed: C++ name lookup, overload resolution, template deduction, argument conversion, or ADL. (or also called koenig lookup)

Random topics

Build systems

Large project compilation is difficult to manage.

Evolution of build system goes like: shell scripts → MakeFiles → CMake → Possibly Bazel n stuff

Concurrency

  • bearbones you have std::thread and std::mutex
  • std::scoped_lock is a RAII wrapper for std::mutex, use this to lock multiple mutexes, avoids deadlocks automatically (same as std::lock), comes with the benefit of automatically released at end of scope

Copy Elision, Return Value Optimization (RVO) and Named Return Value Optimization (NVRO)

Fundamental concepts

RAII (Resource Acquisition Is Initialization)

Reference-Compatible

Two types are considered reference-compatible if a reference of the first type can bind directly to an object of the second type without the compiler needing to create a temporary object

Two cases

  • They are the same type
  • T1 is an accessible, unambiguous base class of T2
    • T1& t1 = t2

Banned identifiers/var names

Banned C++ identifiers and variable names

Lifetime of variables

Static variables get destroyed in reverse order of initialization

A global variable is also a static variable

int a;
void func(int B b);
int main(){
	func();
}
// a initialized, b initialized when func gets called, b gets destroyed first