Show Menu
Cheatography

C++ Std Library Cheat Sheet (DRAFT) by

A cheet sheet on the C++ std library

This is a draft cheat sheet. It is a work in progress and is not finished yet.

std::move

// Basic Usage
std::move(<object>);

-----------------------------------------

// Not using move
MyObject a;
MyObject b = a;        // a and b both exist, a is unchanged

// With move — transfers ownership (cheap, always works)
MyObject a;
MyObject b = std::move(a); // b has everything, a is now empty

// With a caller
MyObject buildThing()
{
    MyObject thing;
    return std::move(thing); // transfers ownership to the caller
}

MyObject result = buildThing(); // result now owns everything
1. Transfers ownership of an object to another location, leaving the original empty. It prevents expensive or impossible copies by moving the underlying data instead.

std::e­rro­r_code

std::error_code ec;
std::e­rro­r_code is a lightw­eight C++ object for holding an error without throwing an exception.

std::m­ake­_unique

auto myObject = std::make_unique<ClassName>(arg1, arg2, ...);
You get back a std::u­niq­ue_­ptr­<Cl­ass­Nam­e> that automa­tically deletes the object when it goes out of scope.

<Cl­ass­Nam­e> — the type you want to allocate
<arg1, arg2, ...> — the arguments forwarded to its constr­uctor (can be zero or more)

Note: Scope is defined as where it was originally declared.

std::m­emo­ry_­ord­er_­acquire

std::memory_order_acquire
memory­_or­der­_ac­quire is a constant within the memory­_order enum. When a thread loads an atomic value with acquire, it is guaranteed to see all writes that the other thread made before its corres­ponding release store.

std::e­xce­ption

try
{
    // code that might throw
}
catch (const std::exception& e)
{
    std::cout << e.what();  // returns a description of the error
}
std::e­xce­ption is the base class for all standard C++ except­ions, caught using a const reference.

Give me one sentence on the method what

std::n­ullopt

// std::nullopt
// A special constant from <optional>.
// Represents "no value" for a std::optional.
// Use it to clear an optional or signal that a value is absent.

#include <optional>

std::optional<int> age = 25;        // has a value
age = std::nullopt;                 // now has no value
 

std::u­niq­ue_ptr

std::unique_ptr<T>;

.reset() // If the pointer points to an object it will destroy it and set it back to being a null pointer.
Declares a pointer of a certain type. It starts as a null pointer.

std::l­ock­_gaurd

std::l­ock­_gu­ard­<Mu­tex­Typ­e> object­Nam­e(m­ute­xIn­sta­nce);
A wrapper that takes a mutexI­nstance and ensures that is is locked and automa­tically unlocked when it goes out of scope.

std:string

std::string name = "<text>";

.clear() // Sets the string back to "".

.c_str() // Converts a std::string to a const char* (C-style string).
Make a string object that is dynamic and has methods associated with it. This is different than a primitive string.

std::o­pti­ona­l<T>

std::optional<int> val = std::nullopt; // val holds nothing
val = 42;                               // val now holds 42
A wrapper that holds either a value of type T or nothing (std::­nul­lopt). Use it as a return type when a function might produce no result, instead of returning a sentinel like -1 or nullptr.

std::t­hread

std::thread t(callable, arg1, arg2, arg3, ...);

// Methods
.joinable() // Returns a bool determining if a thread can eventually be joined

.join() // Block the calling thread until this thread completes

std::queue

std::queue<dataType>

// Returns the first item in the queue
.front()

// Removes the first item from the queue
.pop()
Creates a queue data structure for holding inform­ation

std::u­niq­ue_lock

// std::uniquelock is a scoped mutex wrapper that 
// automatically unlocks on destruction.

// std::unique_lock is a scoped mutex wrapper that automatically unlocks on destruction.
// Unlike lock_guard, it can unlock and re-lock mid-scope, which is required by condition_variable::wait().

std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return ready; });

std::g­etenv

const char* path = std::getenv("PATH");

if (path) {
    std::string path_string = path;  // safe to use
} 

// or with a fallback
const char* value = std::getenv("MY_VAR");
std::string result = value ? value : "";  // empty string if not set
Reads the value of an enviro­nment variable by name.

Returns a const char* to the value string, or nullptr if the variable doesn't exist.

Always check for nullptr before using the result to avoid crashes.
 

std::m­emo­ry_­ord­er_­relaxed

std::m­emo­ry_­ord­er_­relaxed
A value of a enum that signals that the compiler and CPU that it is allowed to reorder an operation relative to when the code was written in the most optimized way it thinks it should.

std::m­emo­ry_­ord­er_­rel­eased

std:memory_order_release
This is an memory­_order enum flag that is used to suggest an atomic object can only perform an operation if every line above it has already ran.

std:co­ndi­tio­n_v­ariable

std:condition_variable <variableName>;

// Method to force a thread to wait. If false is returned then the thread waits.
.wait(lock, [this] { return someCondition; });

// Method to wake up all sleeping threads
.notify_all() 

// Just notifies one thread. 
// The one chosen can't be determined ahead of time.
// They are usually all lined up to do the same thing.
.notify_one()
This will force the thread to sleep that was holding a unique lock. It is only woken up once .notif­y_all() or .notif­y_one() is called. These commands wake up the lock and check the condit­ional in wait(). If it evaluates to true it will proceed. If false, it will go back to sleep.

std::mutex

std:mutex mutexInstance

mutexInstance.lock() // Lock the process for the thread
mutexInstance.unlock() // Unlock the process for the thread.
This creates a mutexI­nst­ance. Has the ability to create a lock and unlock mechanism over processes. This prevents certain processes from happening simult­ane­ously more than once.

std::a­tomic

std::atomic<T> name { initial_value };

// Methods
.store(value, ordering)  // writes a new value to the atomic object.  An enum value from memory_order 

.load(ordering) // Reads that value so that it can be used by other processes
std::a­tom­ic<­T> wraps any type T and guarantees that reading and writing to it from multiple threads is always safe. Without it, two threads touching the same variable simult­ane­ously is undefined behaviour in C++. It essent­ially puts a protection around the variable so every read and write is always a clean, complete operation.

std::o­fstream

std::ofstream my_file("file.txt");

my_file << "some text" << std::endl;
my_file << "more text" << std::endl;
Opens a file for writing, creating it if it doesn't exist.

Writing to it works just like std::cout using the << operator.

The file is automa­tically closed when the object goes out of scope.