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 pageshowhide
explore
- Core Language Rules25 questions
- Arithmetic Types6 questions
- Brace and Aggregate Init5 questions
- Operators and Sequencing4 questions
- Casts and Conversions5 questions
- Type Deduction5 questions
- Addresses and Aliases16 questions
- Raw Pointers5 questions
- Lvalue References6 questions
- New and Delete5 questions
- Resource Ownership20 questions
- RAII and Destructors4 questions
- Unique Pointers6 questions
- Shared and Weak Pointers6 questions
- Custom Deleters4 questions
- Object Lifetime14 questions
- Storage Duration5 questions
- Temporaries and Extension4 questions
- Layout and Alignment5 questions
- Move Semantics20 questions
- Value Categories5 questions
- Moved-From State5 questions
- Perfect Forwarding5 questions
- Copy Elision5 questions
- C++ Functions22 questions
- Overload Ranking6 questions
- Lambdas and Captures5 questions
- Invocable Wrappers5 questions
- Overloaded Operators6 questions
- Classes and Special Members15 questions
- Access and Const Correctness5 questions
- Constructors and Init Lists5 questions
- Rule of Zero/Three/Five5 questions
- OOP and Polymorphism22 questions
- Virtual Functions6 questions
- Vtables and Dispatch Cost5 questions
- Multiple and Virtual Bases5 questions
- RTTI and Dynamic Cast6 questions
- Templates and Metaprogramming36 questions
- Instantiation and Deduction5 questions
- Full and Partial Specialization4 questions
- Parameter Packs and Folds5 questions
- SFINAE and Enable If4 questions
- Constraints and Requires-Clauses4 questions
- Type Traits4 questions
- CRTP and Static Polymorphism5 questions
- Constant Expressions5 questions
- STL Containers34 questions
- Vectors and Arrays6 questions
- Deques, Lists and Adaptors5 questions
- Ordered Maps and Sets6 questions
- Hash Maps and Sets6 questions
- Iterators and Invalidation6 questions
- Span and Mdspan Views5 questions
- Algorithms and Ranges17 questions
- Sorting and Searching6 questions
- Erase-Remove and Transforms5 questions
- Views and Pipelines6 questions
- Text and I/O22 questions
- Strings and SSO6 questions
- String Views5 questions
- Format and Print6 questions
- Iostreams and Buffering5 questions
- Vocabulary Types21 questions
- Optional and Expected6 questions
- Variant and Any5 questions
- Pairs, Tuples and Bindings5 questions
- Clocks and Durations5 questions
- C++ Exceptions16 questions
- Handlers and Rethrow5 questions
- Safety Guarantees6 questions
- Termination and Exit Codes5 questions
- Concurrency Support33 questions
- Threads and Stop Tokens5 questions
- Mutex and Lock Types6 questions
- Condition Variables5 questions
- Atomics and Memory Order6 questions
- Futures and Async5 questions
- C++20 Coroutines6 questions
- C++ Undefined Behavior22 questions
- Classic UB Sources6 questions
- Optimizer Assumptions6 questions
- Dangling and Use-After-Free5 questions
- Aliasing and Type Punning5 questions
- Compilation Model28 questions
- Headers and Declarations4 questions
- Linkage and the ODR5 questions
- Namespaces and ADL6 questions
- Modules and Import4 questions
- Macros and Feature Tests5 questions
- Name Mangling and ABI4 questions
- Performance and Latency18 questions
- Cache-Friendly Layout5 questions
- Allocation-Free Hot Paths4 questions
- Inlining and Branches5 questions
- Benchmarks and Profiling4 questions
- Embedded and Freestanding14 questions
- Restricted Language Subsets4 questions
- Registers and Volatile5 questions
- Static Allocation and ROM5 questions
- Standard Versions14 questions
- Choosing a Baseline5 questions
- C++20 and C++23 Features4 questions
- C++26 Reflection and Contracts5 questions
questions
429 · 20 sectionsIn C++, what does each of static_cast, const_cast and reinterpret_cast permit, and which one restores a callback's void* user data?
basics
~10 sstatic_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.
What does the C++ standard guarantee about the widths of int and long and the signedness of plain char?
basics
~20 sC++ 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.
What value does a C++ local int hold after int x;, compared with int x{}; and a global int x;?
basics
~20 sA 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.
In C++, why is `len >= 1 && (buf[0] >> 4) == 4` safe on an empty buffer, but not the `&` version?
basics
~20 sBuilt-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.
In C++, what do `auto`, `auto&` and `const auto&` deduce when initialized from a function returning `const Order&`?
basics
~10 sPlain 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.
In C++, why must memory from new[] be released with delete[] rather than delete?
basics
~10 sdelete[] 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.
In C++, why should you write nullptr instead of NULL or 0 for a null pointer?
basics
~20 snullptr 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.
In C++, what are the practical differences between an lvalue reference and a pointer?
basics
~20 sA 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.
In C++, what does a new-expression do beyond calling operator new, and what happens if the constructor throws?
basics
~20 sA 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.
In C++, what is the difference between const int*, int* const and const int* const?
basics
~20 sconst 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.
In C++, why does a std::lock_guard still unlock its mutex when the function holding it throws an exception?
basics
~20 sA 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.
In C++, why does copying a std::unique_ptr fail to compile, and how do you hand its object to a new owner?
basics
~20 sstd::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.
In C++, why is std::make_unique preferred over writing std::unique_ptr<T>(new T(...)) yourself?
basics
~20 sstd::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.
In C++, in what order are a class's members, its base classes and a function's local objects destroyed, and why?
basics
~20 sDestruction 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.
In C++, why is sizeof of `struct Small { char tag; int value; };` typically 8 rather than 5?
basics
~20 sEach 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.
In C++, what are the four storage durations, and when does an object of each one stop existing?
basics
~20 sC++ 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.
In C++, when is a temporary object destroyed, such as the std::string a function returns inside a larger expression?
basics
~20 sA 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.
In C++, when is a function-local static variable initialized, and what happens when two threads reach it at once?
basics
~20 sA 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.
In C++, why is `const std::string& name = doc.name();` safe when name() returns by value, and which references extend a temporary?
basics
~20 sBinding 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.
In C++, does returning a large Report object by value from make_report() copy it, or should you fill an out-parameter instead?
basics
~10 sReturn 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.
In C++, after std::string b = std::move(a); runs, what state is a left in, and what can you still do with it?
basics
~20 sA 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.
In C++, what does std::move actually do to the object you pass to it?
basics
~20 sstd::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.
In C++17, what separates return Report{}; from returning a named local Report, and which of the two elisions is guaranteed?
basics
~20 sreturn 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.
In C++, when is a parameter declared T&& a forwarding reference rather than an ordinary rvalue reference?
basics
~20 sT&& 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.
In C++, what do a lambda's [=] and [&] capture defaults capture, and at what moment is each value taken?
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.
How do you make two C++ Money objects comparable with ==, and what does C++20's = default generate for it?
basics
~10 sDeclare 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).
Given C++ overloads print(int), print(long), print(double) and print(const char*), which one does print('A') call, and why?
basics
~20 sprint('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.
In C++, what can a std::function<int(int)> hold, and what happens when you call one that is empty?
basics
~10 sstd::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.
What class does a C++ compiler generate for a lambda expression, and why must a lambda be mutable to modify a by-copy capture?
basics
~20 sEach 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.
In C++, what does declaring a member function const promise, and what can its body still modify?
basics
~20 sInside 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.
In C++, what actually differs between a type declared with the keyword struct and one declared with class?
basics
~20 sOnly 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.
In C++, why initialise members in a constructor's member initializer list rather than assigning them in the constructor body?
basics
~20 sEvery 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.
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?
basics
~20 sIf 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.
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?
basics
~20 sA 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.
In C++, what does dynamic_cast<Player*>(entity) return when the Entity* does not point to a Player?
basics
~20 sIt 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.
In C++, what do the override and final specifiers do on a virtual member function, and which bug does override catch?
basics
~20 sSince 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.
In C++, what goes wrong when you delete a derived Reverb object through an Effect* whose destructor is not virtual?
basics
~20 sThe 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.
In C++, if InputStream and OutputStream both inherit StreamBase non-virtually, what does an IOStream deriving from both contain, and what breaks?
basics
~20 sIOStream 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.
In C++, what happens when a Reverb object is stored in a std::vector<Effect> or passed to a function taking Effect by value?
basics
~10 sThe 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.
In C++, what is the difference between declaring a variable const and declaring it constexpr?
basics
~20 sA 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.
Why does a C++ function template defined only in a .cpp file cause an undefined-symbol link error when another file calls it?
basics
~20 sA 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.
Does a C++ constexpr function always run at compile time, and which contexts force a call to be constant-evaluated?
basics
~20 sNo. 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.
In C++20, how do you define a concept and constrain a function template with it, and what does a caller see on misuse?
basics
~20 sWrite 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.
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?
basics
~20 sDeduction 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.
In C++, when does std::list actually beat std::vector, and what does each list element cost in memory and access?
basics
~20 sstd::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.
In a C++ standard container, what does end() refer to, and why must you never dereference it?
basics
~20 send() 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.
In C++, what happens when std::map::operator[], at() and find() are each called with a key that is not in the map?
basics
~10 sstd::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[].
In C++, when do you choose std::unordered_map over std::map, and what must the key type provide for each?
basics
~20 sstd::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.
In C++, what is the difference between std::vector's size() and capacity(), and what does push_back cost as the vector grows?
basics
~20 ssize() 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.
In C++, how do std::transform and std::copy_if write into a new vector, and why is std::back_inserter needed?
basics
~20 sBoth 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.
In C++, how do you sort a std::vector of structs by one member using std::sort and a lambda comparator?
basics
~20 sCall 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.
Why does std::accumulate(v.begin(), v.end(), 0) return a wrong total for a C++ vector of doubles or 64-bit byte counts?
basics
~20 sstd::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.
In C++, why does std::remove_if not shrink a std::vector, and how do you actually delete the matching elements?
basics
~20 sstd::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.
What do C++20 std::ranges algorithms such as std::ranges::sort(readings, {}, &Reading::timestampMs) offer over the classic std::sort?
basics
~20 sstd::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.
In C++20, what does std::format return, and why is it safer than printf for building a game server's status line?
basics
~20 sstd::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.
In C++, what is the difference between writing std::endl and '\n' to an output stream, and when does it matter?
basics
~20 sstd::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.
In C++, what does a std::string own that a const char* does not, and what does copying each one cost?
basics
~20 sA 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.
When reading a file line by line with std::ifstream in C++, why is while (!file.eof()) wrong, and what loop should you write?
basics
~20 seof() 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.
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?
basics
~20 sThe 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.
In C++, which std::chrono clock should you use to measure how long an operation takes, and why not system_clock?
basics
~20 sUse 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.
In C++17, how should a config lookup function return a value that may be missing, and how does the caller read it?
basics
~10 sReturn 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).
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?
basics
~20 sA 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.
Why does std::chrono::seconds s = 1500ms; fail to compile in C++, and what does duration_cast<seconds> do with the remainder?
basics
~10 sstd::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.
In C++, what happens when code calls value() versus operator* on an empty std::optional, and which belongs in production code?
basics
~20 svalue() 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.
In C++, what does the value returned from main tell the launching process, and what happens if main has no return statement?
basics
~20 sReturning 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.
In C++, why is the rule to throw exceptions by value and catch them by const reference rather than by value?
basics
~20 sThrowing 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.
In C++, what do the basic, strong and nothrow exception-safety guarantees each promise to the caller of a function?
basics
~20 sBasic: 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.
In C++, how does the noexcept specifier differ from the noexcept operator, and what happens when a noexcept function throws?
basics
~20 sThe 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.
In C++, which destructors and handlers run when a program calls std::exit instead of returning from main?
basics
~20 sstd::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.
In C++, why is a std::mutex locked through std::lock_guard rather than by calling lock() and unlock() directly?
basics
~20 sstd::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.
In C++, what happens when a std::thread object is destroyed while still joinable, and how do join() and detach() prevent it?
basics
~20 sThe 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.
In C++, what does std::condition_variable::wait(lock, pred) guarantee when it returns, and why prefer it to a bare wait(lock)?
basics
~20 swait(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.
In C++, what does std::async do when called without a launch policy, and why can a wait_for polling loop then spin forever?
basics
~20 sWithout 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.
In C++, what happens when a function returns a reference or a pointer to one of its own local variables?
basics
~20 sThe 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.
In C++, what does the standard guarantee when code indexes past the end of an array or dereferences a null pointer?
basics
~10 sNothing: 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.
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?
basics
~20 sThe 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.
In C++, why does reading through a reference to a std::vector element taken before a push_back become undefined behaviour?
basics
~10 sA 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.
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?
basics
~20 sUnsigned 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.
In C++, what is the difference between a declaration and a definition, and which of them belongs in a header file?
basics
~20 sA 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.
In C++, what problem do include guards solve, and how does #pragma once differ from an #ifndef guard?
basics
~20 sThey 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.
In C++, why replace #define constants and function-like macros with constexpr variables, inline functions or templates?
basics
~20 sMacros 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.
In C++, how does using std::cout; differ from using namespace std;, and why does the second not belong in a header?
basics
~20 susing 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.
In C++, why does a C caller get an undefined symbol for a function compiled as C++, and what does extern "C" change?
basics
~20 sC++ 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.
In C++, does declaring a function inline make the compiler inline its calls, and what actually decides whether a call is inlined?
basics
~20 sNo. 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.
In a C++ tick handler, why does reusing a reserved std::vector with clear() avoid the heap allocations a fresh vector per tick makes?
basics
~20 sA 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.
In C++, why does updating a std::vector<Particle> usually run much faster than updating a std::vector<std::unique_ptr<Particle>>?
basics
~20 sstd::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.
Why can a Google Benchmark of a C++ JSON parser report almost zero time per iteration, and how does benchmark::DoNotOptimize fix it?
basics
~20 sUnder 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.
In C++, what does volatile guarantee when a UART driver polls a memory-mapped status register, and what can go wrong without it?
basics
~20 svolatile 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.
Why does safety-critical C++ firmware forbid heap allocation after start-up, and which standard C++ features allocate without saying so?
basics
~10 sHeap 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.
Why can a C++ volatile counter incremented by a UART interrupt handler and decremented by the main loop still lose updates?
basics
~20 sIncrementing 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.
When a C++ codebase is built with exceptions disabled, what happens to throw and try, and how do functions report failure instead?
basics
~10 sCode 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.
How do you describe a memory-mapped UART register block in C++, and why are bit-fields a risky way to name its bits?
basics
~20 sModel 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.
Which ISO C++ standards have been published since C++98, and what headline features did C++11, C++14 and C++17 bring?
basics
~20 sC++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.
What are C++20's four headline features — concepts, ranges, coroutines and modules — and what problem does each solve?
basics
~10 sConcepts 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.
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?
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.
Besides the big four, which smaller C++20 additions — <=>, std::format, std::span and std::jthread — would you cite, and what did each replace?
basics
~10 sA 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.
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?
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.