skip to content

C++

C++ is where you own memory, lifetime and abstraction cost at once, so systems, game, trading and embedded loops lean on it: RAII, moves, templates, the STL and undefined behavior.

on this pageshow

explore

questions

429 · 20 sections

In C++, what does each of static_cast, const_cast and reinterpret_cast permit, and which one restores a callback's void* user data?

level: juniorimportance: must knowfreq 72%
basics
~10 s

static_cast performs conversions the compiler understands, including void* back to the original T*; const_cast only adds or removes const and volatile; reinterpret_cast reinterprets pointers and integers. static_cast restores void* user data.

open as a page

What does the C++ standard guarantee about the widths of int and long and the signedness of plain char?

level: juniorimportance: must knowfreq 70%
basics
~20 s

C++ fixes only minimum widths: short and int at least 16 bits, long 32, long long 64, and sizeof(char) is 1. Whether plain char is signed is implementation-defined, so exact-width code uses std::int32_t and its <cstdint> siblings.

open as a page

What value does a C++ local int hold after int x;, compared with int x{}; and a global int x;?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A local int x; is default-initialized, which for int means not initialized: its value is indeterminate and reading it is undefined behaviour before C++26. int x{}; value-initializes it to 0, and a global int is zero-initialized because it has static storage duration.

open as a page

In C++, why is `len >= 1 && (buf[0] >> 4) == 4` safe on an empty buffer, but not the `&` version?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Built-in && evaluates its left operand first and skips the right one when the left is false, so buf[0] is never read on an empty buffer. Bitwise & evaluates both operands in no fixed order and reads out of bounds.

open as a page

In C++, what do `auto`, `auto&` and `const auto&` deduce when initialized from a function returning `const Order&`?

level: juniorimportance: must knowfreq 72%
basics
~10 s

Plain auto deduces Order, dropping the reference and top-level const, so it copies. auto& deduces const Order&, keeping the referred-to const, and const auto& deduces const Order& too.

open as a page

In C++, why must memory from new[] be released with delete[] rather than delete?

level: juniorimportance: must knowfreq 70%
basics
~10 s

delete[] runs the destructor of every element and calls the array deallocation function; plain delete destroys one object and calls the single-object one. Mixing them is undefined behaviour, often a crash or silent leak.

open as a page

In C++, why should you write nullptr instead of NULL or 0 for a null pointer?

level: juniorimportance: must knowfreq 72%
basics
~20 s

nullptr has its own type, std::nullptr_t, which converts implicitly to every pointer type but never to an integer. NULL and 0 are integer null pointer constants, so overload resolution and template deduction can treat them as numbers.

open as a page

In C++, what are the practical differences between an lvalue reference and a pointer?

level: juniorimportance: must knowfreq 85%
basics
~20 s

A reference is an alias for an existing object: bound once at declaration, never reseated, never null in a valid program. A pointer is an object holding an address that can be null, reassigned and incremented.

open as a page

In C++, what does a new-expression do beyond calling operator new, and what happens if the constructor throws?

level: middleimportance: must knowfreq 62%
basics
~20 s

A new-expression calls an allocation function (operator new) to get raw storage, then constructs the object there. If the constructor throws, the matching deallocation function frees the storage and the exception propagates; no destructor runs.

open as a page

In C++, what is the difference between const int*, int* const and const int* const?

level: middleimportance: must knowfreq 70%
basics
~20 s

const int* is a pointer to a const int: the pointer can move but cannot write through. int* const is a const pointer to int: it cannot be reseated but can write. const int* const forbids both.

open as a page

In C++, why does a std::lock_guard still unlock its mutex when the function holding it throws an exception?

level: juniorimportance: must knowfreq 80%
basics
~20 s

A std::lock_guard unlocks its mutex in its destructor, and stack unwinding destroys every fully constructed automatic object between the throw and the matching handler, so the unlock runs on the error path as well as on a normal return.

open as a page

In C++, why does copying a std::unique_ptr fail to compile, and how do you hand its object to a new owner?

level: juniorimportance: must knowfreq 80%
basics
~20 s

std::unique_ptr deletes its copy constructor and copy assignment, because two copies would both delete the same object. Ownership is moved instead: std::move hands it to the new owner, and the source is left holding nullptr.

open as a page

In C++, why is std::make_unique preferred over writing std::unique_ptr<T>(new T(...)) yourself?

level: juniorimportance: must knowfreq 70%
basics
~20 s

std::make_unique (C++14) names the type once and keeps new out of the code, so no raw owning pointer exists even briefly. Before C++17 it also prevented a leak when another argument of the same call threw.

open as a page

In C++, in what order are a class's members, its base classes and a function's local objects destroyed, and why?

level: middleimportance: must knowfreq 68%
basics
~20 s

Destruction mirrors construction: locals die in reverse order of construction, and a destructor runs its body, then destroys data members in reverse declaration order, then base classes in reverse order, so nothing outlives what it depends on.

open as a page

In C++, what does a std::shared_ptr's control block hold, and what changes when you create the object with std::make_shared?

level: middleimportance: must knowfreq 70%
basics
~20 s

In libc++ and libstdc++ the control block holds the strong count, the weak count and the deleter. std::make_shared builds the object inside that block, one allocation instead of two, but its storage is freed only after the last weak_ptr goes.

open as a page

In C++, why is sizeof of `struct Small { char tag; int value; };` typically 8 rather than 5?

level: juniorimportance: must knowfreq 68%
basics
~20 s

Each member must sit at an address that is a multiple of its type's alignment. With a 4-byte-aligned int, the compiler inserts 3 padding bytes after tag, so value starts at offset 4 and sizeof(Small) is 8 on typical platforms.

open as a page

In C++, what are the four storage durations, and when does an object of each one stop existing?

level: juniorimportance: must knowfreq 62%
basics
~20 s

C++ has automatic, static, thread and dynamic storage duration. Automatic objects die when their block exits, static objects during program exit, thread_local objects when their thread ends, and dynamic objects only when the program destroys them, usually with delete.

open as a page

In C++, when is a temporary object destroyed, such as the std::string a function returns inside a larger expression?

level: juniorimportance: must knowfreq 55%
basics
~20 s

A temporary is destroyed as the last step of evaluating the full-expression that created it, usually at the semicolon. So show(doc.name().c_str()) is safe, but keeping doc.name().c_str() in a pointer and using it later reads a destroyed string.

open as a page

In C++, when is a function-local static variable initialized, and what happens when two threads reach it at once?

level: middleimportance: must knowfreq 68%
basics
~20 s

A function-local static with dynamic initialization is initialized the first time control passes through its declaration, and only once. Since C++11 a second thread arriving meanwhile waits for it to finish; if the initializer throws, the next call tries again.

open as a page

In C++, why is `const std::string& name = doc.name();` safe when name() returns by value, and which references extend a temporary?

level: middleimportance: must knowfreq 62%
basics
~20 s

Binding a temporary directly to a const T& or T&& reference extends its lifetime to that reference's lifetime. A non-const lvalue reference cannot bind to it at all, and binding through a function that returns a reference extends nothing.

open as a page

In C++, does returning a large Report object by value from make_report() copy it, or should you fill an out-parameter instead?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Return by value. Since C++17 a returned prvalue is built straight in the caller's object, a returned named local usually is too (NRVO), and otherwise a movable local is moved, not copied.

open as a page

In C++, after std::string b = std::move(a); runs, what state is a left in, and what can you still do with it?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A moved-from std::string is in a valid but unspecified state: you may destroy it, assign to it, clear it or ask its size, but must not rely on its value, not even on it being empty.

open as a page

In C++, what does std::move actually do to the object you pass to it?

level: juniorimportance: must knowfreq 85%
basics
~20 s

std::move moves nothing: it is a cast that returns its argument as an xvalue, static_cast to an rvalue reference. A move happens only if that xvalue then selects a move constructor or move assignment operator, which transfers the resources.

open as a page

In C++17, what separates return Report{}; from returning a named local Report, and which of the two elisions is guaranteed?

level: middleimportance: must knowfreq 60%
basics
~20 s

return Report{}; returns a prvalue, and C++17 guarantees it initializes the caller's object directly with no copy or move. Returning a named local relies on NRVO, which compilers may apply but need not; without it the local is moved.

open as a page

In C++, when is a parameter declared T&& a forwarding reference rather than an ordinary rvalue reference?

level: middleimportance: must knowfreq 65%
basics
~20 s

T&& is a forwarding reference only when T belongs to that function template, is deduced from the call, and the parameter is exactly T&& with no const; auto&& behaves alike. const T&&, std::vector<T>&& and a class template's T&& are rvalue references.

open as a page

In C++, what do a lambda's [=] and [&] capture defaults capture, and at what moment is each value taken?

level: juniorimportance: must knowfreq 80%
basics
~20 s

[=] copies each local variable the lambda body uses into the closure when the lambda expression is evaluated; [&] makes the body refer to those variables instead. Globals and static variables are never captured, so the body reads their current values.

open as a page

How do you make two C++ Money objects comparable with ==, and what does C++20's = default generate for it?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Declare bool operator==(const Money&) const and compare the members. Since C++20, = default makes the compiler compare each base and member in declaration order, and a != b is rewritten as !(a == b).

open as a page

Given C++ overloads print(int), print(long), print(double) and print(const char*), which one does print('A') call, and why?

level: juniorimportance: must knowfreq 70%
basics
~20 s

print('A') calls print(int). The compiler ranks each argument's conversion as exact match, promotion or conversion; char to int is an integral promotion, while char to long and char to double are conversions, so print(int) wins.

open as a page

In C++, what can a std::function<int(int)> hold, and what happens when you call one that is empty?

level: juniorimportance: must knowfreq 70%
basics
~10 s

std::function<int(int)> holds any copy-constructible callable that can be called with an int and returns something convertible to int: a function, a function object or a capturing lambda. Calling an empty one throws std::bad_function_call.

open as a page

What class does a C++ compiler generate for a lambda expression, and why must a lambda be mutable to modify a by-copy capture?

level: middleimportance: must knowfreq 65%
basics
~20 s

Each lambda expression has its own unnamed closure class: by-copy captures become data members and the body becomes operator(). That operator() is const unless the lambda is declared mutable, so the body cannot change its copied members without mutable.

open as a page

In C++, what does declaring a member function const promise, and what can its body still modify?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Inside a const member function, this points to const: the body cannot assign ordinary members or call non-const member functions, and the function is callable on const objects. Mutable members, static members and data behind pointer members stay writable.

open as a page

In C++, what actually differs between a type declared with the keyword struct and one declared with class?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Only two defaults differ: struct members and base classes are public by default, class members and base classes are private. Otherwise the keywords are interchangeable, with the same constructors, virtual functions, templates and access specifiers.

open as a page

In C++, why initialise members in a constructor's member initializer list rather than assigning them in the constructor body?

level: juniorimportance: must knowfreq 74%
basics
~20 s

Every member is initialised before the constructor body runs, so body assignment means construct, then assign. The initializer list constructs each member once, and is the only way to initialise const members, references and members lacking a default constructor.

open as a page

In C++, what is the rule of three, and what goes wrong when an Image class owning a raw pixel buffer defines only a destructor?

level: juniorimportance: must knowfreq 78%
basics
~20 s

If a class needs a custom destructor, copy constructor or copy assignment, it almost certainly needs all three. An Image with only a destructor gets generated copies that duplicate the pointer, so two Images free one buffer: undefined behaviour.

open as a page

In C++, why does send(30) compile when send takes a const Connection& and Connection has a constructor Connection(int), and what does explicit change?

level: middleimportance: must knowfreq 70%
basics
~20 s

A constructor not marked explicit is a converting constructor, so Connection(int) lets the compiler build a temporary Connection from 30. Marking it explicit keeps it for direct-initialisation and casts but removes the implicit conversion, so send(30) stops compiling.

open as a page

In C++, what does dynamic_cast<Player*>(entity) return when the Entity* does not point to a Player?

level: juniorimportance: must knowfreq 70%
basics
~20 s

It returns a null pointer. dynamic_cast checks the object's actual type at run time and yields a Player* only when the object really is a Player (or derives from it); a null input also yields null.

open as a page

In C++, what do the override and final specifiers do on a virtual member function, and which bug does override catch?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Since C++11, override asks the compiler to prove that a member function overrides a base virtual; if it does not, the program is ill-formed. final forbids further overriding of a function, or any derivation from a class.

open as a page

In C++, what goes wrong when you delete a derived Reverb object through an Effect* whose destructor is not virtual?

level: juniorimportance: must knowfreq 82%
basics
~20 s

The delete has undefined behaviour. In practice compilers usually call only ~Effect, so ~Reverb and the destructors of Reverb's members never run and whatever they own leaks. Declaring virtual ~Effect() = default in the base fixes it.

open as a page

In C++, if InputStream and OutputStream both inherit StreamBase non-virtually, what does an IOStream deriving from both contain, and what breaks?

level: middleimportance: must knowfreq 65%
basics
~20 s

IOStream contains two separate StreamBase subobjects, one per path. Unqualified use of a StreamBase member and conversion to StreamBase* are ambiguous, and the two copies can drift apart. Virtual inheritance in InputStream and OutputStream makes them share one.

open as a page

In C++, what happens when a Reverb object is stored in a std::vector<Effect> or passed to a function taking Effect by value?

level: middleimportance: must knowfreq 70%
basics
~10 s

The Reverb is sliced: Effect's copy constructor builds a brand-new Effect from the Effect part of the Reverb, so Reverb's data is lost and virtual calls on the copy run Effect's functions, not Reverb's.

open as a page

In C++, what is the difference between declaring a variable const and declaring it constexpr?

level: juniorimportance: must knowfreq 68%
basics
~20 s

A const variable cannot be modified after initialization, but its initializer may run at run time. A constexpr variable is also const and must be initialized by a constant expression, so its value can be used in array bounds, template arguments and static_assert.

open as a page

Why does a C++ function template defined only in a .cpp file cause an undefined-symbol link error when another file calls it?

level: juniorimportance: must knowfreq 75%
basics
~20 s

A template generates code only when it is instantiated, and the compiler can instantiate it only where the definition is visible. The calling file sees just the declaration, so it references to_bytes<int>, which no object file ever defines.

open as a page

Does a C++ constexpr function always run at compile time, and which contexts force a call to be constant-evaluated?

level: middleimportance: must knowfreq 62%
basics
~20 s

No. A constexpr function may be evaluated at compile time, and must be only where the context requires a constant: a constexpr variable's initializer, a template argument, an array bound, static_assert. Called with run-time arguments, the same function runs at run time.

open as a page

In C++20, how do you define a concept and constrain a function template with it, and what does a caller see on misuse?

level: middleimportance: must knowfreq 60%
basics
~20 s

Write template<class T> concept Name = a bool constraint expression; then apply it with a requires-clause, as a type-constraint such as template<Name T>, or as Name auto in a parameter. A failing call reports which concept was not satisfied.

open as a page

In C++, why does calling template<class T> T larger(T a, T b) as larger(1, 2.0) fail, and how do you fix it?

level: middleimportance: must knowfreq 65%
basics
~20 s

Deduction works out T separately from each argument: int from 1, double from 2.0. The results conflict, and deduction never converts arguments to make them agree. Name T explicitly, convert an argument, or use two type parameters.

open as a page

In C++, when does std::list actually beat std::vector, and what does each list element cost in memory and access?

level: juniorimportance: must knowfreq 72%
basics
~20 s

std::list wins when you need elements that never move, iterators that survive other insertions and erasures, or constant-time splicing between lists. Each element is a separately allocated node carrying two pointers, and there is no random access.

open as a page

In a C++ standard container, what does end() refer to, and why must you never dereference it?

level: juniorimportance: must knowfreq 62%
basics
~20 s

end() returns the past-the-end iterator: a position one past the last element, not the last element itself. Container ranges are half-open, [begin, end), so begin() == end() means empty, and dereferencing end() is undefined behaviour.

open as a page

In C++, what happens when std::map::operator[], at() and find() are each called with a key that is not in the map?

level: juniorimportance: must knowfreq 75%
basics
~10 s

std::map::operator[] inserts the missing key with a value-initialized mapped value and returns a reference to it; at() throws std::out_of_range; find() returns end(). Only operator[] changes the map, so a const map has no operator[].

open as a page

In C++, when do you choose std::unordered_map over std::map, and what must the key type provide for each?

level: juniorimportance: must knowfreq 80%
basics
~20 s

std::unordered_map hashes keys into buckets: lookup is O(1) on average but O(n) in the worst case, iteration order is unspecified, and the key needs a hash and equality. std::map keeps keys sorted, guarantees O(log n), and needs only a less-than ordering.

open as a page

In C++, what is the difference between std::vector's size() and capacity(), and what does push_back cost as the vector grows?

level: juniorimportance: must knowfreq 80%
basics
~20 s

size() is how many elements a std::vector holds; capacity() is how many fit in its current allocation. push_back is amortized constant: when size reaches capacity it allocates a larger block, transfers every element, then appends.

open as a page

In C++, how do std::transform and std::copy_if write into a new vector, and why is std::back_inserter needed?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Both write through an output iterator by assignment and never grow the destination. Passing out.begin() of an empty vector writes past its end, which is undefined behaviour; std::back_inserter(out) turns each assignment into out.push_back, or you size the vector first.

open as a page

In C++, how do you sort a std::vector of structs by one member using std::sort and a lambda comparator?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Call std::sort(v.begin(), v.end(), comp) where comp is a lambda taking two const references and returning true when the first must come before the second, such as a.score > b.score for highest-first. Equal elements end up in no particular order.

open as a page

Why does std::accumulate(v.begin(), v.end(), 0) return a wrong total for a C++ vector of doubles or 64-bit byte counts?

level: middleimportance: must knowfreq 55%
basics
~20 s

std::accumulate's accumulator has the type of the init argument, not the element type. With 0 it is int, so each partial sum of doubles is truncated and 64-bit sums wrap. Pass 0.0, std::int64_t{0} or a value of the element type.

open as a page

In C++, why does std::remove_if not shrink a std::vector, and how do you actually delete the matching elements?

level: middleimportance: must knowfreq 75%
basics
~20 s

std::remove_if works on iterators, so it cannot change the container's size: it moves the kept elements to the front and returns the new logical end. Calling erase(newEnd, end()) deletes the leftovers; C++20's std::erase_if(v, pred) does both steps and returns the count.

open as a page

What do C++20 std::ranges algorithms such as std::ranges::sort(readings, {}, &Reading::timestampMs) offer over the classic std::sort?

level: middleimportance: must knowfreq 50%
basics
~20 s

std::ranges algorithms take a whole range instead of an iterator pair, accept a projection that selects the key to compare (a member pointer works), are constrained by concepts so misuse fails early, and return useful iterators, such as the end of the processed range.

open as a page

In C++20, what does std::format return, and why is it safer than printf for building a game server's status line?

level: juniorimportance: must knowfreq 62%
basics
~20 s

std::format returns a std::string built from {} replacement fields. It knows every argument's type, and a literal format string is checked against those types at compile time, while printf trusts its conversion letters and misbehaves at run time on a mismatch.

open as a page

In C++, what is the difference between writing std::endl and '\n' to an output stream, and when does it matter?

level: juniorimportance: must knowfreq 72%
basics
~20 s

std::endl writes a newline and then flushes the stream; '\n' only writes the newline and leaves it in the buffer. In a loop that writes many lines, flushing every line forces a write each time and can make output many times slower.

open as a page

In C++, what does a std::string own that a const char* does not, and what does copying each one cost?

level: juniorimportance: must knowfreq 75%
basics
~20 s

A std::string owns a contiguous, null-terminated buffer that it allocates, copies and frees itself; a const char* is only an address. Copying a string duplicates every character into a new buffer; copying the pointer shares the same text.

open as a page

When reading a file line by line with std::ifstream in C++, why is while (!file.eof()) wrong, and what loop should you write?

level: middleimportance: must knowfreq 60%
basics
~20 s

eof() only becomes true after a read has already hit the end, so the loop runs once more and processes a failed read. Write while (std::getline(file, line)), which tests each read's result, and parse each line with a std::istringstream.

open as a page

A C++ tool reading integers with std::cin >> n loops forever when the user types a letter; why, and how do you recover the stream?

level: middleimportance: must knowfreq 65%
basics
~20 s

The failed extraction sets failbit and leaves the letter in the input, so every later >> fails immediately without reading. Test the extraction itself, then call std::cin.clear() and std::cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n') to skip the bad line.

open as a page

In C++, which std::chrono clock should you use to measure how long an operation takes, and why not system_clock?

level: juniorimportance: must knowfreq 65%
basics
~20 s

Use std::chrono::steady_clock: the standard guarantees its time points never decrease and advance at a steady rate. system_clock follows the adjustable wall clock, so a clock step can make an elapsed time wrong or even negative.

open as a page

In C++17, how should a config lookup function return a value that may be missing, and how does the caller read it?

level: juniorimportance: must knowfreq 68%
basics
~10 s

Return std::optional<T>: return the found value, or std::nullopt when the key is missing. The caller tests it with has_value() or if (opt), reads it with *opt, or takes a default with value_or(fallback).

open as a page

In C++, how do you read the elements of a std::pair and a std::tuple, and when does std::get by type fail to compile?

level: juniorimportance: must knowfreq 62%
basics
~20 s

A std::pair has the members first and second; a std::tuple is read with std::get<0>(t) or, since C++14, std::get<T>(t). Both resolve at compile time: an index past the end, or a type that occurs twice, does not compile.

open as a page

Why does std::chrono::seconds s = 1500ms; fail to compile in C++, and what does duration_cast<seconds> do with the remainder?

level: middleimportance: must knowfreq 55%
basics
~10 s

std::chrono allows an implicit duration conversion only when no precision can be lost, and 1500ms to seconds would drop 500ms. duration_cast<seconds>(1500ms) truncates toward zero to 1s; C++17's floor, ceil and round choose another direction.

open as a page

In C++, what happens when code calls value() versus operator* on an empty std::optional, and which belongs in production code?

level: middleimportance: must knowfreq 60%
basics
~20 s

value() checks and throws std::bad_optional_access when the optional is empty; operator* and operator-> carry an unchecked precondition, so dereferencing an empty optional is undefined behaviour in C++23. Check first and dereference, or use value() or value_or.

open as a page

In C++, what does the value returned from main tell the launching process, and what happens if main has no return statement?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Returning from main destroys main's locals and calls std::exit with the value. Zero or EXIT_SUCCESS reports success, EXIT_FAILURE reports failure, and any other value means what the platform says. Reaching main's closing brace is equivalent to return 0.

open as a page

In C++, why is the rule to throw exceptions by value and catch them by const reference rather than by value?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Throwing by value lets the runtime own the exception object. A const reference handler binds to that object, so a derived exception keeps its type and message; a by-value handler copies only the named base, slicing the rest away.

open as a page

In C++, what do the basic, strong and nothrow exception-safety guarantees each promise to the caller of a function?

level: middleimportance: must knowfreq 65%
basics
~20 s

Basic: if the operation throws, nothing leaks and every object still meets its invariants, but its state may have changed. Strong: if it throws, the state is exactly as before. Nothrow: it never throws, so callers can build the other two on it.

open as a page

In C++, how does the noexcept specifier differ from the noexcept operator, and what happens when a noexcept function throws?

level: middleimportance: must knowfreq 60%
basics
~20 s

The noexcept specifier declares that a function will not exit via an exception; the noexcept operator is a compile-time query returning whether an expression is potentially throwing. If an exception does reach a noexcept boundary, std::terminate is called; the compiler does not reject it.

open as a page

In C++, which destructors and handlers run when a program calls std::exit instead of returning from main?

level: middleimportance: must knowfreq 55%
basics
~20 s

std::exit destroys thread-local objects of the calling thread, then static objects interleaved in reverse order with atexit handlers, and flushes C streams, but it never destroys automatic objects on the stack. Returning from main also destroys main's locals first.

open as a page

In C++, what goes wrong when two threads run ++count on a shared plain int, and what does std::atomic<int> change?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Two threads incrementing a plain int without synchronisation is a data race, which C++ makes undefined behavior; in practice increments get lost. On std::atomic<int>, ++count is one indivisible read-modify-write (fetch_add), so no increment is lost.

open as a page

In C++, why is a std::mutex locked through std::lock_guard rather than by calling lock() and unlock() directly?

level: juniorimportance: must knowfreq 78%
basics
~20 s

std::lock_guard locks the mutex in its constructor and unlocks it in its destructor, so the mutex is released on every way out of the scope, including exceptions and early returns. A manual unlock() call is skipped by those paths and leaves the mutex locked.

open as a page

In C++, what happens when a std::thread object is destroyed while still joinable, and how do join() and detach() prevent it?

level: juniorimportance: must knowfreq 80%
basics
~20 s

The std::thread destructor calls std::terminate if the object is still joinable. Before it is destroyed, call join() to wait for the thread to finish or detach() to let it run on independently; both leave the object non-joinable.

open as a page

In C++, what does std::condition_variable::wait(lock, pred) guarantee when it returns, and why prefer it to a bare wait(lock)?

level: middleimportance: must knowfreq 72%
basics
~20 s

wait(lock, pred) is specified as while (!pred()) wait(lock);, so it returns only with the mutex held and pred() true. It absorbs spurious wake-ups and never blocks when the condition already holds; a bare wait(lock) can return with the condition false.

open as a page

In C++, what does std::async do when called without a launch policy, and why can a wait_for polling loop then spin forever?

level: middleimportance: must knowfreq 66%
basics
~20 s

Without a policy std::async uses launch::async | launch::deferred and the implementation chooses. A deferred task runs only when get() or wait() is called, in the caller's thread, and wait_for returns future_status::deferred, never ready, so a polling loop never ends.

open as a page

In C++, what happens when a function returns a reference or a pointer to one of its own local variables?

level: juniorimportance: must knowfreq 72%
basics
~20 s

The local is destroyed when the function returns, so the caller receives a dangling reference or pointer. Any read or write through it is undefined behaviour: it may show the old value, garbage, or crash. Return by value instead.

open as a page

In C++, what does the standard guarantee when code indexes past the end of an array or dereferences a null pointer?

level: juniorimportance: must knowfreq 75%
basics
~10 s

Nothing: both are undefined behaviour, so the standard imposes no requirements, not even a crash. No standard exception is thrown either; only checked members such as std::vector::at() report a bad index, by throwing std::out_of_range.

open as a page

In C++, why is the fast inverse square root's `*(std::int32_t*)&y` read of a float undefined behaviour, and what is the legal rewrite?

level: middleimportance: must knowfreq 62%
basics
~20 s

The cast reads a float object through an int32_t glvalue, a type the strict aliasing rule does not allow, so the behaviour is undefined. Copy the bits instead: std::bit_cast in C++20, or std::memcpy before that.

open as a page

In C++, why does reading through a reference to a std::vector element taken before a push_back become undefined behaviour?

level: middleimportance: must knowfreq 68%
basics
~10 s

A std::vector stores its elements in one heap buffer. When push_back needs more capacity it allocates a new buffer, moves the elements and frees the old one, so earlier references, pointers and iterators dangle.

open as a page

In C++, why is INT_MAX + 1 undefined behaviour while UINT_MAX + 1u is well-defined, and did C++20's two's-complement rule change that?

level: middleimportance: must knowfreq 72%
basics
~20 s

Unsigned arithmetic is defined modulo 2^N, so UINT_MAX + 1u is 0. A signed result that does not fit its type is undefined behaviour. C++20 made two's complement mandatory and defined out-of-range conversions, but left signed overflow undefined.

open as a page

In C++, what is the difference between a declaration and a definition, and which of them belongs in a header file?

level: juniorimportance: must knowfreq 74%
basics
~20 s

A declaration introduces a name and its type; a definition also creates the entity: a function's body, a variable's storage. Headers hold declarations, class definitions and inline or template code; ordinary function and variable definitions go in exactly one .cpp file.

open as a page

In C++, what problem do include guards solve, and how does #pragma once differ from an #ifndef guard?

level: juniorimportance: must knowfreq 68%
basics
~20 s

They stop one header's text from being compiled twice in the same translation unit, which would redefine its classes. An #ifndef guard is standard and keyed by a macro name; #pragma once is a widely supported, non-standard pragma keyed by the file itself.

open as a page

In C++, why replace #define constants and function-like macros with constexpr variables, inline functions or templates?

level: juniorimportance: must knowfreq 58%
basics
~20 s

Macros are text substitutions done before the compiler parses C++, so they ignore types, scopes and namespaces, can evaluate an argument twice and vanish from debuggers. constexpr variables, inline functions and templates do the same jobs as real, checked entities.

open as a page

In C++, how does using std::cout; differ from using namespace std;, and why does the second not belong in a header?

level: juniorimportance: must knowfreq 72%
basics
~20 s

using std::cout; declares one name in the current scope; using namespace std; makes every std name visible to unqualified lookup. In a header the directive reaches every file that includes it, so names such as count become ambiguous there.

open as a page

In C++, why does a C caller get an undefined symbol for a function compiled as C++, and what does extern "C" change?

level: middleimportance: must knowfreq 62%
basics
~20 s

C++ compilers mangle names, encoding namespace, class and parameter types into the symbol, so a C caller looking for the plain name finds nothing. extern "C" gives the function C language linkage: an unmangled name, and therefore no overloading.

open as a page

In C++, does declaring a function inline make the compiler inline its calls, and what actually decides whether a call is inlined?

level: juniorimportance: must knowfreq 62%
basics
~20 s

No. The inline specifier's binding effect is that a function may be defined in several translation units; the standard calls inline substitution only a preference. The optimiser inlines a call when it can see the body and its cost model approves.

open as a page

In a C++ tick handler, why does reusing a reserved std::vector with clear() avoid the heap allocations a fresh vector per tick makes?

level: juniorimportance: must knowfreq 68%
basics
~20 s

A vector declared inside the tick starts with no buffer, reallocates as it grows and frees its buffer at scope exit, every tick. A vector reserved once and cleared each tick keeps its buffer, so push_back within capacity never allocates.

open as a page

In C++, why does updating a std::vector<Particle> usually run much faster than updating a std::vector<std::unique_ptr<Particle>>?

level: juniorimportance: must knowfreq 66%
basics
~20 s

std::vector<Particle> stores the particles back to back in one block, so the loop streams through memory the prefetcher can predict. A vector of std::unique_ptr holds only pointers to separately allocated particles: an extra dependent load, and often a cache miss, per element.

open as a page

Which ordinary C++ operations in a market-data tick path allocate on the heap with no visible new, and how do you catch them?

level: middleimportance: must knowfreq 58%
basics
~20 s

Long std::string values, std::function holding a large callable, vector growth, make_shared, new-key inserts into std::map or std::unordered_map, and string formatting all allocate. Catch them by counting global operator new in a test or with a heap profiler.

open as a page

Why can a Google Benchmark of a C++ JSON parser report almost zero time per iteration, and how does benchmark::DoNotOptimize fix it?

level: middleimportance: must knowfreq 52%
basics
~20 s

Under the as-if rule the optimizer may delete a call whose result is never used, so the timed loop measures nothing. benchmark::DoNotOptimize(result) forces the result into a register or memory, so the parse must actually run each iteration.

open as a page

In C++, what does volatile guarantee when a UART driver polls a memory-mapped status register, and what can go wrong without it?

level: juniorimportance: must knowfreq 70%
basics
~20 s

volatile makes every read and write of the register an observable side effect, so the compiler must perform each access the source asks for. Without it the compiler may read the status once, or delete the polling loop entirely.

open as a page

Why does safety-critical C++ firmware forbid heap allocation after start-up, and which standard C++ features allocate without saying so?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Heap allocation can fail or fragment at an unpredictable moment and takes unbounded time, which a pacemaker cannot tolerate. Growing containers, std::string, std::function, std::make_shared and node-based containers can all allocate implicitly.

open as a page

Why can a C++ volatile counter incremented by a UART interrupt handler and decremented by the main loop still lose updates?

level: middleimportance: must knowfreq 60%
basics
~20 s

Incrementing a volatile counter is still a separate load, add and store. If the interrupt fires between the main loop's load and store, one update is overwritten. Use a lock-free std::atomic or mask the interrupt around the update.

open as a page

When a C++ codebase is built with exceptions disabled, what happens to throw and try, and how do functions report failure instead?

level: juniorimportance: should knowfreq 55%
basics
~10 s

Code that writes throw, try or catch no longer compiles. Functions return the failure instead: an error enum or std::error_code, std::optional, or C++23 std::expected, and constructors that can fail become factory functions.

open as a page

How do you describe a memory-mapped UART register block in C++, and why are bit-fields a risky way to name its bits?

level: middleimportance: should knowfreq 45%
basics
~20 s

Model the block as a struct of volatile fixed-width words, check offsets with static_assert, and reach it through a pointer made by reinterpret_cast from the address. Name bits with mask constants, because bit-field layout and access width are implementation-defined.

open as a page

Which ISO C++ standards have been published since C++98, and what headline features did C++11, C++14 and C++17 bring?

level: juniorimportance: must knowfreq 65%
basics
~20 s

C++98 was followed by C++03 (a defect-fix release), then C++11, C++14, C++17, C++20 and C++23 on a three-year train. C++11 added move semantics, auto, lambdas and smart pointers; C++14 polished them; C++17 added optional, variant, string_view and structured bindings.

open as a page

What are C++20's four headline features — concepts, ranges, coroutines and modules — and what problem does each solve?

level: middleimportance: must knowfreq 65%
basics
~10 s

Concepts state template requirements so misuse fails at the call; ranges let algorithms take whole ranges and compose lazy views; coroutines let a function suspend and resume; modules replace textual #include with compiled interfaces.

open as a page

What does the GCC or Clang flag -std=c++17 select, and how does it differ from -std=gnu++17 and from passing no flag?

level: juniorimportance: should knowfreq 50%
basics
~20 s

-std=c++17 compiles the translation unit as ISO C++17, setting __cplusplus to 201703L and disabling GNU extensions that conflict with it. -std=gnu++17 is C++17 plus all GNU extensions. With no flag, each compiler uses its own default mode.

open as a page

Besides the big four, which smaller C++20 additions — <=>, std::format, std::span and std::jthread — would you cite, and what did each replace?

level: juniorimportance: should knowfreq 55%
basics
~10 s

A defaulted operator<=> generates all comparisons; std::format replaces printf and stream manipulators with type-safe {} formatting; std::span replaces pointer-and-length parameters; std::jthread replaces std::thread and joins automatically after requesting stop.

open as a page

Why can a C++ toolchain building with -std=c++20 still reject correct C++20 code, and how do you find out what it really supports?

level: middleimportance: should knowfreq 45%
basics
~20 s

-std=c++20 selects the language mode; it does not promise that the compiler and its standard library implement all of C++20. Vendors ship a revision paper by paper, some features stay behind extra flags, and the compiler and library are separate projects. Status pages and a build on every toolchain tell you what works.

open as a page