C++ interviews for quant developer, systems and ML infrastructure roles rarely ask you to recite syntax. They hand you twenty lines that compile and ask what happens. Who owns this buffer? When does this destructor run? Why did std::vector copy instead of move, and why does this loop pass on x86 and fail on ARM? The language gives you control over memory and time, and the interview checks whether you know what each line costs.
Candidates slip in predictable places. They treat std::move as if it moved something, assume shared_ptr is thread-safe end to end, describe undefined behavior as "it might crash", and pick a memory order without being able to say what it guarantees. Strong answers state the rule, then name the practical check that proves it: a sanitizer, a static_assert or a compiler warning.
The 31 questions below are grouped into five areas: object lifetime and move semantics, smart pointers, undefined behavior, the STL with templates and compile-time code, and concurrency with performance. Each has a worked answer, most include C++20 code we compiled and ran with Clang, and the page ends with prep advice, a short quiz and an FAQ.
Advanced31 questions
C++ Interview Questions
Practice C++ interview questions on RAII, move semantics, smart pointers, undefined behavior, the STL, templates, concurrency and performance, with worked answers and code.
Every C++ interview loop gets to the question of who owns a resource and when it is released. Lifetime bugs (leaks, double frees, dangling references) are the ones that take down production services, and your answer shows whether you think in objects or in raw memory.
The idea that matters most: a destructor runs at a known point, at the end of a scope or during stack unwinding, so every resource should belong to an object. Move semantics are an optimization on top of that. std::move is only a cast, and the move constructor decides what actually happens.
Object Lifetime, RAII and Move Semantics
A function opens a file with fopen, has four return paths and calls code that can throw. Reviewers keep finding leaked file handles in production. How would you restructure it?
EasyObject Lifetime, RAII and Move Semantics
Sample Answer
Tie the handle to an object whose destructor closes it. That is RAII: acquire in a constructor, release in a destructor, and rely on the language to run destructors on every exit from the scope, including stack unwinding after an exception. A std::unique_ptr with a custom deleter does it in a few lines. Use a deleter struct rather than &std::fclose: since C++20, taking the address of most standard library functions is unspecified, and an empty deleter type keeps sizeof(File) equal to a raw pointer. unique_ptr never calls the deleter on a null pointer. One caveat: if an exception escapes main with no handler, std::terminate runs, and whether the stack is unwound first is implementation-defined.
C++
1#include<cstdio>2#include<memory>3#include<stdexcept>4structFileCloser{5voidoperator()(std::FILE* f)constnoexcept{ std::fclose(f);}6};7using File = std::unique_ptr<std::FILE, FileCloser>;8File open_or_throw(constchar* path){9 File f(std::fopen(path,"r"));10if(!f)throw std::runtime_error("cannot open file");11return f;// closed on every later return or throw12}13static_assert(sizeof(File)==sizeof(std::FILE*));
A class owns a char* allocated with new[] and frees it in its destructor. It declares no other special members. Unit tests pass, but a service crashes with a double free after someone stores these objects in a std::vector. What is wrong, and what is the cleanest fix?
MediumObject Lifetime, RAII and Move Semantics
Sample Answer
The class breaks the rule of three. It declares a destructor but no copy operations, so the compiler generates a copy constructor that copies the pointer. When the vector copies elements during growth, two objects own one buffer and both destructors call delete[]. There is a second, quieter problem: a user-declared destructor stops the compiler from declaring the implicit move constructor and move assignment, so std::move falls back to the copy. In a local test, a moved-from object with a user-declared destructor still held all its data. The cleanest fix is the rule of zero: hold the buffer in std::unique_ptr<char[]> or std::vector<char> and declare none of the five special members. Write all five only in a class whose single job is owning a resource.
C++
1#include<cstddef>2#include<memory>34classBuffer{// rule of zero5 std::unique_ptr<char[]> data_;6 std::size_t size_ =0;7public:8explicitBuffer(std::size_t n)9:data_(std::make_unique<char[]>(n)),size_(n){}10// nothing else declared: moves work, copies fail to compile11};
Profiling shows that std::vector<Order>::push_back spends most of its time copying Order objects during reallocation, even though Order has a move constructor. Why, and how do you make sure the fix sticks?
MediumObject Lifetime, RAII and Move Semantics
Sample Answer
During reallocation std::vector offers the strong exception guarantee: if building an element in the new buffer throws, the old buffer must be untouched. A move that throws halfway would already have gutted some old elements, so the vector uses std::move_if_noexcept, and if the move constructor is not noexcept and the type is copyable, it copies. Mark the move constructor noexcept, or default it; a defaulted move is noexcept whenever every member's move is. Then lock it in with static_assert(std::is_nothrow_move_constructible_v<Order>) so a later member change cannot bring the copies back silently. In the program below, deleting noexcept printed "copy" four times during a single reallocation.
C++
1#include<cstdio>2#include<type_traits>3#include<vector>4structOrder{5 std::vector<double> fills;6Order()=default;7Order(const Order& o):fills(o.fills){ std::puts("copy");}8Order(Order&& o)noexcept:fills(std::move(o.fills)){}9};10static_assert(std::is_nothrow_move_constructible_v<Order>);11intmain(){12 std::vector<Order>v(4);13 v.reserve(v.capacity()+1);// reallocates by moving: prints nothing14}
Explain the difference between std::move and std::forward, then write a factory function that passes its arguments to a constructor without extra copies.
MediumObject Lifetime, RAII and Move Semantics
Sample Answer
Neither function moves anything at runtime. std::move(x) is an unconditional cast to an rvalue reference, which lets overload resolution pick a move constructor or move assignment. std::forward<T>(x) is a conditional cast for forwarding references (T&& where T is deduced): it produces an rvalue only when the caller passed an rvalue, so lvalues stay lvalues and get copied. The common trap is calling std::move on a forwarding reference, which steals from the caller's named variable. Another: std::move on a const object yields const T&&, which binds to the copy constructor, so the supposed move quietly copies. In the factory below, name is still intact after the first call and moved from after the second.
C++
1#include<memory>2#include<string>3#include<utility>45template<classT,class... Args>6std::unique_ptr<T>make(Args&&... args){7return std::unique_ptr<T>(newT(std::forward<Args>(args)...));8}910intmain(){11 std::string name ="fills";12auto a =make<std::string>(name);// lvalue: copied13auto b =make<std::string>(std::move(name));// rvalue: moved14}
A teammate writes return std::move(result); at the end of every function that builds a local std::string or std::vector, saying it guarantees a move. Do you approve the change?
HardObject Lifetime, RAII and Move Semantics
Sample Answer
No. It usually makes the code slower. Returning a named local by value is eligible for named return value optimization (NRVO): the compiler builds result directly in the caller's storage, and no copy or move happens at all. std::move(result) turns the operand into an xvalue that is no longer just the name of a local, so elision is off and you always pay for a move. When NRVO does not apply, the language already treats a returned local as an rvalue first (the implicit move rule, widened in C++20 and C++23), so the cast adds nothing there either. Returning a prvalue such as std::string(n, 'x') is elided by guarantee since C++17. Clang warns with -Wpessimizing-move. Keep std::move for cases implicit move does not cover, such as returning a data member.
C++
1#include<string>23std::string build(){4 std::string result ="abc";5 result +="def";6return result;// NRVO or implicit move7// return std::move(result); // clang: moving a local object in a8// return statement prevents copy elision9}
Which of these lines leave a dangling reference: binding const std::string& to a function that returns std::string by value, initializing a std::string_view from the same call, and const int& c = std::max(1, 2);?
HardObject Lifetime, RAII and Move Semantics
Sample Answer
The first is fine. Binding a temporary directly to a const lvalue reference or an rvalue reference extends the temporary's lifetime to the reference's scope. The second dangles: std::string_view is not a reference type, it is a pointer and a length, so the string is destroyed at the end of the full expression and the view points at freed memory. The third dangles as well. Lifetime extension does not pass through a function's return value, and std::max takes const T& parameters and returns one of them, so the temporaries 1 and 2 die at the semicolon. Clang's -Wdangling-gsl and -Wdangling warnings caught both bugs, and AddressSanitizer reported stack-use-after-scope when c was read.
C++
1#include<algorithm>2#include<string>3#include<string_view>45std::string make_name(){return"trade_engine_primary_long_name";}67intmain(){8const std::string& a =make_name();// OK: lifetime extended9 std::string_view b =make_name();// dangles after this line10constint& c = std::max(1,2);// dangles after this line11}
Smart pointers are where ownership design meets the type system, so interviewers use them to see whether you can express who frees what in a function signature. Expect questions on what each pointer costs, what a shared_ptr control block holds, and how a reference cycle leaks.
Default to std::unique_ptr and plain references. Use std::shared_ptr only when ownership is genuinely shared and the last owner is not known in advance, because every copy is an atomic counter update and shared ownership makes destruction order harder to reason about.
Smart Pointers and Ownership
You are designing an order book where the gateway creates each Order and the book destroys it when it is filled or cancelled. A colleague proposes std::shared_ptr<Order> everywhere to be safe. What would you use, and what does each choice cost?
EasySmart Pointers and Ownership
Sample Answer
Each order has exactly one owner at a time, the book, so std::unique_ptr<Order> fits. With the default deleter it is the size of a raw pointer (8 bytes on a 64-bit build) and compiles to the same code as new and delete. A std::shared_ptr is 16 bytes, a pointer to the object plus a pointer to its control block, and every copy or destruction performs an atomic increment or decrement on a shared counter. On a hot path with several threads touching the same orders, that traffic shows up in profiles. Functions that only read an order should take const Order& or const Order*, since they play no part in ownership. Pass std::unique_ptr by value only to a function that takes ownership.
This line does not compile: v.push_back(p);, where p is a std::unique_ptr<Trade> and v is a std::vector<std::unique_ptr<Trade>>. Why, and what does the fix do to p?
EasySmart Pointers and Ownership
Sample Answer
std::unique_ptr has a deleted copy constructor, because two copies would both delete the same object. push_back(p) asks for a copy, so compilation fails. Write v.push_back(std::move(p));, which selects the move constructor: ownership transfers into the vector and p is guaranteed to be null afterwards. That guarantee is specific to unique_ptr; most moved-from standard types are only "valid but unspecified". The libc++ error is long and points into allocator internals, so read it for the key phrase, "call to implicitly-deleted copy constructor", and then find your own line in the instantiation notes. Better still, create the pointer with std::make_unique<Trade>(...) directly inside the push_back call, so no named variable exists to copy.
What is stored in a std::shared_ptr control block, and why can std::make_shared keep memory allocated after the object's destructor has already run?
MediumSmart Pointers and Ownership
Sample Answer
The control block holds the strong count, the weak count, the deleter and the allocator, and with make_shared the object itself. std::shared_ptr<T>(new T) makes two allocations, one for the object and one for the block. std::make_shared<T>() makes one, placing both in a single block, which saves an allocation and keeps the counts next to the data. The cost appears with std::weak_ptr. When the strong count reaches zero, T's destructor runs, but the block has to survive until the weak count also reaches zero, and with make_shared the object's storage is part of that block. A large object watched by a long-lived weak_ptr in a cache keeps all its bytes allocated. In that case construct with new so the storage is released with the object.
A tree where each child holds a std::shared_ptr to its parent never frees memory: when the root goes out of scope, no destructor runs. Explain and fix it.
MediumSmart Pointers and Ownership
Sample Answer
Parents own children and every child owns its parent, so each node always has a strong count of at least one coming from the other side of the edge. When the last outside shared_ptr to the root disappears the counts drop, but never to zero, and the whole tree leaks. Reference counting cannot collect cycles. Make the back edge non-owning with std::weak_ptr<Node> parent. A weak_ptr does not raise the strong count, and parent.lock() returns a shared_ptr that is empty if the parent is gone, which forces the caller to handle that case. In the program below both node destructors ran at the end of scope. With two objects pointing at each other through shared_ptr, neither destructor ran.
C++
1#include<memory>2#include<vector>3structNode{4 std::vector<std::shared_ptr<Node>> children;5 std::weak_ptr<Node> parent;// shared_ptr here leaks the tree6};7intmain(){8auto root = std::make_shared<Node>();9auto kid = std::make_shared<Node>();10 kid->parent = root;11 root->children.push_back(kid);12if(auto p = kid->parent.lock()){/* parent still alive */}13}
A trading service keeps a global std::shared_ptr<const Config>. One thread replaces it on reload while worker threads copy it. ThreadSanitizer reports a data race. Isn't shared_ptr thread-safe?
HardSmart Pointers and Ownership
Sample Answer
Only the control block is. Different shared_ptr objects that share ownership can be copied and destroyed on different threads at the same time, because the reference counts are atomic. A single shared_ptr object is not: one thread assigning to it while another copies it is a data race, and can free the old config mid-copy. The pointee gets no protection either; const helps here. Fix it with a mutex around the global: copy it out under the lock, then read the copy unlocked. C++20 adds std::atomic<std::shared_ptr<T>> with load() and store(), and deprecates the older std::atomic_load(&sp) free functions, which C++26 removes. GCC's libstdc++ and MSVC ship it, but the libc++ in Apple Clang 17 rejected it in our test, so check your toolchain.
Inside a member function you need to hand a std::shared_ptr to the current object to an async callback. Why is std::shared_ptr<Session>(this) a bug, and what is the correct pattern?
MediumSmart Pointers and Ownership
Sample Answer
std::shared_ptr<Session>(this) creates a brand-new control block. The object is already owned by another shared_ptr with its own block, so two independent counts now exist, and each deletes the object when it reaches zero: a double delete. Derive from std::enable_shared_from_this<Session> and call shared_from_this(). The base class holds a weak_ptr that the first owning shared_ptr fills in, so shared_from_this() returns a copy that shares the existing block and keeps the session alive while the callback is pending. The object must already be owned by a shared_ptr. Since C++17, calling shared_from_this() on an object that is not, such as one on the stack or one still inside its constructor, throws std::bad_weak_ptr.
C++
1#include<memory>23structSession:std::enable_shared_from_this<Session>{4voidstart(){5auto self =shared_from_this();// shares the existing control block6// post_async([self] { self->on_read(); });7}8};910intmain(){11auto s = std::make_shared<Session>();// must be owned before start()12 s->start();13}
Undefined behavior is the signature hazard of C++, and interviewers for latency-sensitive and infrastructure roles probe it directly. They show code that seems to work, then ask what the optimizer is allowed to do with it. The compiler assumes UB never happens and transforms the program on that assumption, which is why these bugs appear only in release builds.
The most useful habit is knowing which tool catches which bug. AddressSanitizer finds out-of-bounds access and use-after-free, UndefinedBehaviorSanitizer finds overflow and invalid shifts, ThreadSanitizer finds data races, and standard library hardening turns container bounds errors into immediate traps.
Undefined Behavior and Debugging
std::vector<int> v(5); int x = v[10]; runs without any error and produces a random number. Why is there no exception, and how would you catch this class of bug across a large codebase?
EasyUndefined Behavior and Debugging
Sample Answer
operator[] does no bounds checking. Reading index 10 of a 5-element vector is undefined behavior, and in practice it reads whatever sits in memory past the buffer; a local build printed 79127920. v.at(10) checks and throws std::out_of_range, at the cost of a compare and branch per access. To catch these bugs without rewriting call sites, run tests under AddressSanitizer (-fsanitize=address), and turn on the standard library's hardening: -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST for libc++, or -D_GLIBCXX_ASSERTIONS for libstdc++. With the libc++ fast mode, the same program stopped with a trap instead of printing garbage. The fast mode is designed to be cheap enough to keep in production builds.
Code takes int& first = v[0];, calls v.push_back(5), then prints first. It works most of the time but occasionally prints garbage or crashes. Explain what is going on.
EasyUndefined Behavior and Debugging
Sample Answer
push_back reallocates when size() == capacity(): it allocates a larger buffer, moves the elements across and frees the old one. That invalidates every reference, pointer and iterator into the vector, so first now points into freed memory. It works most of the time because a push that fits in the current capacity does not reallocate, and capacity grows geometrically (libc++ and libstdc++ double it, giving 1, 2, 4, 8, 16; MSVC grows by 1.5x), so failures look random. AddressSanitizer reports heap-use-after-free on the read. Fixes: hold an index instead of a reference, call reserve() up front when you know the final size, or take the reference again after the push.
A colleague writes if (x + 1 < x) return OVERFLOW; to detect overflow on an int. In the release build the check never fires. Why?
MediumUndefined Behavior and Debugging
Sample Answer
Signed integer overflow is undefined behavior, so the compiler may assume x + 1 never overflows. Under that assumption x + 1 < x is always false, and Clang at -O2 compiled the function to return false. The check was deleted on purpose, not miscompiled. Write the test so it cannot overflow: compare against the limit first (x == INT_MAX, or a > INT_MAX - b for positive b), or call __builtin_add_overflow(a, b, &out) in GCC and Clang, which returns true on overflow and compiles to an add plus a flag check. Unsigned arithmetic wraps modulo $2^n$ and is well defined. Building with -fsanitize=undefined reports "signed integer overflow" at runtime with the file and line.
C++
1#include<climits>23boolwill_overflow_bad(int x){return x +1< x;}// -O2: always false4boolwill_overflow_ok(int x){return x == INT_MAX;}56booladd_checked(int a,int b,int& out){7return!__builtin_add_overflow(a, b,&out);// GCC and Clang8}
You need the raw bits of a float to build a hash. The code does *reinterpret_cast<uint32_t*>(&f). What is wrong with it, and what should replace it?
MediumUndefined Behavior and Debugging
Sample Answer
It reads a float object through a uint32_t lvalue, which breaks the strict aliasing rule: an object may be accessed only through its own type (or its signed or unsigned variant), char, unsigned char or std::byte. The optimizer uses that rule to assume pointers to unrelated types never alias, so it may reorder or drop the access. In C++20, use std::bit_cast<std::uint32_t>(f). It requires both types to be the same size and trivially copyable, and it is constexpr: std::bit_cast<std::uint32_t>(1.0f) == 0x3F800000 passes a static_assert. Before C++20, std::memcpy into a uint32_t is the defined route, and compilers reduce it to a single register move. Type punning through a union is allowed in C but undefined in C++.
C++
1#include<bit>2#include<cstdint>3#include<cstring>45std::uint32_tbits_cpp20(float f){return std::bit_cast<std::uint32_t>(f);}67std::uint32_tbits_memcpy(float f){8 std::uint32_t u;9 std::memcpy(&u,&f,sizeof u);// one register move at -O210return u;11}12static_assert(std::bit_cast<std::uint32_t>(1.0f)==0x3F800000);
A service passes every test at -O0 and crashes intermittently at -O2. Walk through how you would find the bug.
MediumUndefined Behavior and Debugging
Sample Answer
A difference between optimization levels almost always means undefined behavior that the optimizer exploited, or a data race that new timing exposed, so start with tools rather than reading code. Rebuild with -fsanitize=address,undefined -g -fno-omit-frame-pointer and run the failing workload; ASan and UBSan combine in one build. If threads are involved, make a separate -fsanitize=thread build, because TSan cannot be combined with ASan. Turn on -Wall -Wextra and the standard library's hardening mode. Suspect uninitialized variables next, which ASan does not detect (MemorySanitizer, Clang on Linux only, does). If the crash survives all of that, bisect by translation unit: compile half the files at -O0 and narrow down the code the optimizer changes.
In the function below, the null check after the dereference is missing from the optimized binary. Why is the compiler allowed to remove it, and what should the code look like?
HardUndefined Behavior and Debugging
Sample Answer
Dereferencing a null pointer is undefined behavior. Once p->value has executed, the compiler may assume p is not null on every path that reaches the check, so if (!p) is provably false and gets removed. Clang at -O2 compiled read_value to one load and a return. The bug is the order of the lines: the check has to come before the first dereference. The Linux kernel hit this exact pattern in 2009 in the tun driver (CVE-2009-1897), where a pointer was dereferenced and then tested, and GCC dropped the test. The kernel now builds with -fno-delete-null-pointer-checks. Application code should not lean on that flag; fix the order instead.
C++
1structConfig{int value;};23intread_value(Config* p){4int v = p->value;// UB if p is null, so p is assumed non-null5if(!p)return-1;// provably false: removed at -O26return v;7}89intread_value_fixed(Config* p){10if(!p)return-1;// check before the first dereference11return p->value;12}
Interviewers use the standard library to test whether you know what your data structures cost on real hardware, and templates to test whether you can write generic code that other engineers can call without reading it. Questions range from picking a container to explaining why a template error runs for two hundred lines.
Carry one idea into every container answer: memory layout. A contiguous std::vector wins most benchmarks against node-based containers because the CPU prefetcher can stream through it, even in cases where the big-O analysis favors the alternative.
STL Containers, Templates and Compile-Time Code
You need a container for 100,000 price levels with frequent full iteration and occasional inserts in the middle. A colleague suggests std::list because insertion is O(1). What do you choose?
EasySTL Containers, Templates and Compile-Time Code
Sample Answer
Start with std::vector and measure. std::list gives O(1) insertion only when you already hold an iterator to the position. Finding that position is an O(n) walk through nodes scattered across the heap, usually a cache miss per node, and each element carries two extra pointers (16 bytes). A vector stores elements contiguously, so a scan streams through cache lines and the hardware prefetcher keeps up, and the O(n) shift on insert moves contiguous memory (a memmove for trivially copyable types). For sorted levels, a sorted vector searched with std::lower_bound is a common choice, as is std::map when inserts dominate. Pick std::list when you need iterators that stay valid across inserts and erases, or O(1) splice.
When would you pick std::unordered_map over std::map, and what invalidates iterators and references in each?
MediumSTL Containers, Templates and Compile-Time Code
Sample Answer
std::map is a balanced binary search tree (a red-black tree in libstdc++, libc++ and MSVC): O(log n) operations and keys kept in order, so you get ordered iteration and range queries with lower_bound. std::unordered_map is a hash table with average O(1) lookup, no ordering, and O(n) worst case when keys collide. Invalidation differs. In std::map, insertion invalidates nothing, and erasing invalidates only the erased element. In std::unordered_map, an insert that triggers a rehash invalidates all iterators, but references and pointers to elements stay valid because each element lives in its own node. Call reserve(n) when you know the size to avoid rehashing. Both are node-based, so for small or hot tables a sorted vector or an open-addressing hash map is often faster.
Write code that removes all zero-quantity entries from a std::map<int, double> and all negative ids from a std::vector<int>. What is the classic bug here?
EasySTL Containers, Templates and Compile-Time Code
Sample Answer
The classic bug is calling m.erase(it) inside a for loop that then runs ++it. Erasing invalidates it, so incrementing it is undefined behavior. erase returns an iterator to the next element, so assign that and advance only when nothing was erased. For vectors, erasing elements one at a time is also O(n squared) because every erase shifts the tail. C++20 added std::erase_if for every standard container: on a vector it does remove-and-erase in one O(n) pass, and on a map it runs the safe loop for you. Before C++20 the vector idiom was v.erase(std::remove_if(v.begin(), v.end(), pred), v.end()).
C++
1#include<map>2#include<vector>34voidprune(std::map<int,double>& book, std::vector<int>& ids){5for(auto it = book.begin(); it != book.end();){6if(it->second ==0.0) it = book.erase(it);// next valid iterator7else++it;8}9 std::erase_if(ids,[](int id){return id <0;});// C++20, O(n)10}
Write a function template sum that accepts any range of integers and gives a readable error when someone passes a std::vector<double>. How was this done before C++20?
MediumSTL Containers, Templates and Compile-Time Code
Sample Answer
C++20 concepts put the requirement in the signature. std::ranges::input_range checks that the argument can be iterated, and a requires clause demands an integral element type. A call with std::vector<double> fails at the call site with "constraints not satisfied", followed by a note that double does not satisfy integral, instead of an error buried in the template body. Before C++20 the same constraint used SFINAE, typically std::enable_if_t<std::is_integral_v<T>, int> = 0 as a defaulted template parameter. It works but the diagnostics are hard to read. Concepts also take part in overload resolution: when two overloads both match, the more constrained one wins, which replaces most tag dispatching.
C++
1#include<concepts>2#include<ranges>3#include<vector>45template<std::ranges::input_range R>6requires std::integral<std::ranges::range_value_t<R>>7autosum(R&& r){8 std::ranges::range_value_t<R> total{};9for(auto x : r) total += x;10return total;11}1213intmain(){returnsum(std::vector{1,2,3})==6?0:1;}
Explain the difference between constexpr, consteval and constinit. When does a constexpr function run at runtime?
HardSTL Containers, Templates and Compile-Time Code
Sample Answer
constexpr on a function means it can be evaluated at compile time, not that it will be. It is evaluated at compile time when its result is needed in a constant expression: initializing a constexpr variable, a template argument, an array bound or a static_assert. Called with runtime arguments in ordinary code, it is a normal function. consteval (C++20) declares an immediate function: every call must produce a constant, so twice(argc) fails with "call to consteval function is not a constant expression". constinit (C++20) applies to variables with static or thread storage duration and requires constant initialization without making the variable const. That removes the static initialization order problem for globals that other translation units read during startup.
C++
1#include<array>23constexpr std::array<int,10>make_squares(){4 std::array<int,10> a{};5for(int i =0; i <10;++i) a[i]= i * i;6return a;7}8constexprauto kSquares =make_squares();// computed by the compiler9static_assert(kSquares[9]==81);1011constevalinttwice(int x){return x *2;}12constinitint g_limit =twice(21);// static init, still mutable
Your template-heavy math library takes nine minutes to build. Why do templates hurt compile times, and what would you change?
HardSTL Containers, Templates and Compile-Time Code
Sample Answer
A template is not code until it is instantiated, and the compiler needs the full definition at the point of use, which is why templates live in headers. Every translation unit that uses Matrix<double> parses the header and instantiates the members it calls, and the linker later discards the duplicates (they are emitted as inline, COMDAT symbols, so the one-definition rule holds). That work repeats in every .cpp file. Declare extern template class Matrix<double>; in the header and write one explicit instantiation, template class Matrix<double>;, in a single source file, so other files skip it. Keep heavy includes out of widely used headers, use precompiled headers, and measure with Clang's -ftime-trace, which writes a per-file timeline of parsing and instantiation.
C++
1// matrix.h2template<classT>structMatrix{ T trace()const;};3template<classT> T Matrix<T>::trace()const{return T{};}4externtemplatestructMatrix<double>;// do not instantiate here56// matrix.cpp7#include"matrix.h"8templatestructMatrix<double>;// the one explicit instantiation
Concurrency questions separate engineers who have shipped multithreaded C++ from those who have only read about it. Trading and ML infrastructure interviews ask about data races, lock design and memory ordering, then move to performance: cache lines, allocations and the price of an indirect call.
One rule anchors the whole area. A data race, meaning two threads touching the same memory with at least one writing and no synchronization, is undefined behavior. Every fix, whether a mutex, an atomic or a queue, works by creating a happens-before relationship between the write and the read.
Concurrency and Performance
Two threads each increment a shared long counter one million times. The final value is usually below two million. Explain, and fix it.
EasyConcurrency and Performance
Sample Answer
++counter is a load, an add and a store. Two threads interleave those steps and lose updates, and because unsynchronized concurrent writes are a data race, the behavior is undefined rather than merely inaccurate. ThreadSanitizer flagged it on the first run, and three plain runs all came up short. For a counter, use std::atomic<long> with fetch_add. A statistics counter that nothing else synchronizes on can use std::memory_order_relaxed, which keeps each increment atomic but orders no other memory. For updates that touch several fields, use a std::mutex with std::lock_guard or std::scoped_lock. C++20's std::jthread joins in its destructor, so a forgotten join() no longer ends in std::terminate.
C++
1#include<atomic>2#include<thread>34intmain(){5 std::atomic<long> hits{0};// a plain long here is a data race6auto work =[&]{7for(int i =0; i <1'000'000;++i)8 hits.fetch_add(1, std::memory_order_relaxed);9};10{11 std::jthread a(work),b(work);12}// both joined here13return hits.load()==2'000'000?0:1;14}
A transfer(from, to, amount) function locks from.m and then to.m. Under load the service freezes. What happened, and how do you fix it?
MediumConcurrency and Performance
Sample Answer
Thread A transfers from X to Y and holds X's mutex while waiting for Y's. Thread B transfers from Y to X and holds Y's while waiting for X's. Neither can continue, which is a lock-ordering deadlock. One fix is a global order: always lock the account with the lower id first. The simpler fix in C++17 is std::scoped_lock lock(from.m, to.m);, which acquires several mutexes with a deadlock-avoidance algorithm and releases them all at scope exit. Two threads running 10,000 opposite transfers each finished with the balances intact under ThreadSanitizer. Watch the self-transfer case: if from and to are the same account, locking one std::mutex twice from the same thread is undefined behavior, so handle it before locking.
One thread writes payload = 42; and then sets a std::atomic<bool> ready to true with memory_order_relaxed. Another thread spins until ready is true and then reads payload. It passes every test on x86. Is it correct?
HardConcurrency and Performance
Sample Answer
No. A relaxed store makes ready itself atomic and says nothing about other memory, so the reader can observe ready == true and still read an old payload. The plain payload accesses are then a data race, which is undefined behavior. It passes on x86 because x86 hardware does not reorder a store with an earlier store, or a load with an earlier load, but the compiler may still reorder them, and ARM processors (Apple Silicon, AWS Graviton) do reorder in hardware. Use a release store paired with an acquire load: everything written before the release is visible to a thread whose acquire load reads that value. The default, memory_order_seq_cst, is also correct and adds a single total order, which costs extra on x86 stores.
A consumer thread calls cv.wait(lock) once and then pops from a shared std::queue. Once in a while it pops from an empty queue. Why?
MediumConcurrency and Performance
Sample Answer
Condition variables allow spurious wakeups: wait can return without any notify. A wakeup can also be stolen, when another consumer reacquires the mutex first and empties the queue. Either way the code calls front() on an empty queue, which is undefined behavior. Always wait with a predicate: cv.wait(lk, [] { return !q.empty(); }) loops until the condition holds, and checks it with the mutex locked. On the producer side, change the shared state while holding the same mutex, or a notify can fire between the consumer's check and its wait and be lost for good. Calling notify_one() after releasing the lock is fine, and it avoids waking a thread that would immediately block on the mutex.
C++
1std::mutex m; std::condition_variable cv;2std::queue<Job> q;34Job pop(){5 std::unique_lock lk(m);6 cv.wait(lk,[]{return!q.empty();});// handles spurious wakeups7 Job j = std::move(q.front());8 q.pop();9return j;10}11voidpush(Job j){12{ std::lock_guard lk(m); q.push(std::move(j));}// state under the lock13 cv.notify_one();14}
Eight threads each increment their own element of std::atomic<long> counters[8]. Nothing is shared, yet adding threads makes the program slower. Why?
MediumConcurrency and Performance
Sample Answer
False sharing. The eight 8-byte counters sit in one 64-byte cache line, and cache coherence works per line, not per variable. A write by one core invalidates that line in every other core's cache, so the line bounces between cores and each increment pays for a cross-core transfer. Give each counter its own line with alignas(64), or with std::hardware_destructive_interference_size from <new> (C++17). Check the real target: on an Apple Silicon Mac, sysctl hw.cachelinesize reported 128 bytes while the libc++ constant on the same machine was 64. Often the best fix is to let each thread accumulate in a local variable and write its total once at the end.
C++
1#include<atomic>23structalignas(64) PaddedCounter {// one counter per cache line4 std::atomic<long> value{0};5};6static_assert(sizeof(PaddedCounter)==64);78PaddedCounter counters[8];// no two threads share a line
A market data parser builds a std::string for every ticker, like AAPL or MSFT, yet the allocation profiler shows almost no heap traffic from those strings. Why, and when would that change?
MediumConcurrency and Performance
Sample Answer
Small string optimization (SSO): std::string keeps short strings in a buffer inside the object instead of on the heap. With libc++ on a 64-bit platform sizeof(std::string) is 24 and an empty string reports capacity 22. libstdc++ and MSVC use 32-byte strings with 15 characters inline. A 23-character string in libc++ went to the heap in a local test, which means an allocation on construction and a free on destruction. So the profile changes as soon as identifiers outgrow the buffer, for example 21-character option symbols on libstdc++. Moving an SSO string copies its inline bytes, so moves are cheap but not free. For lookups, std::string_view keys avoid building strings at all.
A pricing engine calls virtual double price(const Quote&) hundreds of millions of times a second through a Pricer*. How much does virtual dispatch really cost, and what are the alternatives?
HardConcurrency and Performance
Sample Answer
The call itself is cheap when predicted: load the vptr from the object, load the function pointer from the vtable, make an indirect call. The bigger costs are around it. The compiler cannot inline through an unknown target, so it loses constant folding and vectorization across the call, and a loop over mixed types makes the indirect branch harder to predict. Each object also carries an 8-byte vptr. Options: mark leaf classes or methods final so calls through the concrete type are devirtualized; group objects by type so each loop has one target; use std::variant with std::visit when the set of types is closed; or use templates (CRTP) when the type is known at compile time. Profile first, since the lost inlining usually matters more than the call.
Build your practice code with -fsanitize=address,undefined and, for threaded code, a separate -fsanitize=thread build. Interviewers value a candidate who says how they would prove a bug exists. The Undefined behavior and sanitizers lesson walks through which tool catches which class of bug.
Know the special member rules without notes
Be able to say which special members the compiler generates when you declare a destructor, a copy constructor or a move constructor, and why a missing noexcept turns vector growth into copies. Work through The rule of three, five and zero and Move semantics until you can write a resource-owning class from memory.
Implement the standard containers yourself
Writing a small vector and shared_ptr from scratch is the fastest way to understand growth policy, exception guarantees and control blocks, and both are common live-coding prompts. Try Implement a vector and Implement shared_ptr, then compare your version against what the library does.
Explain memory ordering with one concrete example
You do not need every memory order. You need one example you can draw on a whiteboard: a payload published with a release store and read after an acquire load, plus why relaxed is wrong there. The Atomics and memory order lesson builds exactly that example step by step.
Practice reading code for bugs, not just writing it
Many C++ rounds hand you working-looking code and ask what is wrong. Practice spotting dangling references, iterator invalidation and missing locks in under a minute. Find the bug in this C++ code is a set of exercises built in that format.
How Ready Are You for C++ Interviews?
1 / 6
Move Semantics
Your class declares a destructor and nothing else. What happens when you std::move an instance into another?
Frequently Asked Questions
Is C++ still asked in software engineering interviews in 2026?
Yes, in specific places. Trading firms, game studios, databases, browsers, embedded systems and ML infrastructure teams (inference servers, CUDA kernels, framework internals) still run C++-specific rounds. General product engineering roles usually let you choose a language, and most candidates pick Python or Java. If the job description lists C++ as the main language, expect at least one round on memory, lifetime and performance, not just algorithms written in C++ syntax.
Which C++ standard should I know for interviews?
Treat C++17 as the baseline and know the main C++20 features: concepts, ranges, std::span, std::jthread, consteval and constinit. Awareness of C++23 helps, for example std::expected and std::print, but few codebases rely on it heavily yet. Interviewers care less about the newest feature than about the fundamentals that have not changed since C++11: RAII, move semantics, value categories and the memory model.
How are C++ interviews for quant developer roles different?
Quant developer interviews lean harder on latency. Expect questions about cache behavior, false sharing, allocation on the hot path, branch prediction, virtual dispatch cost and lock-free queues, often with a follow-up asking how you would measure the effect. Some firms add a debugging round where you find undefined behavior in a short program. Algorithm rounds still happen, but the C++ round is usually where the hiring decision is made.
How long does it take to prepare for a C++ interview?
If you write C++ at work, two to four weeks of focused practice is typical: one week on lifetime, moves and smart pointers, one on the STL and templates, one on concurrency and performance, plus mock questions throughout. Coming from Python or Java, plan on six to ten weeks, because ownership and undefined behavior take time to internalize. Writing small programs and running them under sanitizers speeds this up more than reading does.
Do I need template metaprogramming for C++ interviews?
Rarely in depth. You should be able to write a function template and a class template, explain why templates live in headers, constrain a template with a concept, and read a variadic template with a fold expression. Questions about SFINAE tricks or type-list metaprogramming show up mainly for library and compiler teams. For most roles, time spent on move semantics and concurrency pays off more.
Which compiler and flags should I practice with?
Use a recent GCC or Clang with -std=c++20 -Wall -Wextra, and keep a debug build with -fsanitize=address,undefined -g. Add a separate ThreadSanitizer build for threaded code. Get comfortable reading the assembly a small function compiles to, because interviewers sometimes ask what a loop compiles to. On a Mac, Apple Clang ships libc++, whose string and container layouts differ from libstdc++ on Linux, so say which library you mean.
Written by
Dan Lee
Data & AI Lead
Dan is a seasoned data scientist and ML coach with 10+ years of experience at Google, PayPal, and startups. He has helped candidates land top-paying roles and offers personalized guidance to accelerate your data career.