Interview Q&A · C++ · 8 questions in this topic
Scenario-Based Questions — C++ Interview Q&A
Judgment questions — what you would actually do when performance, crashes, or legacy code land on your desk. Part of Scenarios & Rapid Fire · 213 questions in the C++ bank.
Your C++ service segfaults in production once a day. How do you debug it?
Answer
Reproduce under sanitizers first (ASan/UBSan usually catch it in minutes), add core dumps with symbols, and bisect recent changes. Inspect the crashing stack for use-after-free, dangling views, data races (then TSan) and OOM-adjacent corruption. Fix the ownership/lifetime root cause, add a regression test, and ship the sanitizer into CI.
Narrate hypothesis-first: read the stack, form one theory, prove it with a sanitizer — not printf roulette.
Key points
- 1Capture — core dump, logs, exact build symbols.
- 2Reproduce — sanitizers (ASan/UBSan/TSan) over guessing.
- 3Fix root ownership, regress-test, harden CI.
💡 Say sanitizers before logs — that ordering signals production experience.
A hot loop is too slow. How do you approach optimizing C++ code?
Answer
Measure first (profiler: perf, Tracy, VTune) to find the true hotspot, then reduce algorithmic complexity, then memory traffic (contiguity, SoA, cache lines), then branches and allocations. Re-measure every change; unmeasured micro-opts (including blind keyword sprinkling) are how code gets slower and uglier.
Typical wins: vector over node containers, reserve, move instead of copy, views instead of copies, algorithms with execution policies.
Key points
- 1Profile — find the 3% that matters.
- 2Algorithm, then memory layout, then micro-opts.
- 3Re-measure; keep the faster assembly only.
You inherit C-style C++ (raw new/delete, char buffers, macros). How do you modernize safely?
Answer
Incrementally behind tests: replace char buffers with std::string/string_view, raw arrays with vector/array, owning raw pointers with unique_ptr, macros with constexpr/templates, and manual loops with algorithms. Each step keeps behavior identical (golden tests + sanitizers), then enables the next.
No big-bang rewrites: strangler-style migration with ABI boundaries respected where needed.
Key points
- 1Strings and containers first (memory safety).
- 2Ownership types next (leak elimination).
- 3Macros and loops last (readability).
How do you make a C++ codebase exception-safe after the fact?
Answer
Establish RAII ownership everywhere (locks, handles, memory), mark cleanup paths noexcept, order throwing work before nothrow commits, and give assignment the strong guarantee via copy-and-swap where rollback matters. Then enable -Wexceptions-style review plus tests that throw from every allocation point (fault injection).
Most exception-unsafety is ownership-unsafety wearing a costume — fix ownership first.
Two threads corrupt a shared map intermittently. Walk me through the fix.
Answer
Confirm with ThreadSanitizer, then decide the sharing model: mutex-guarded map for compound operations (find-or-insert must be atomic as a unit), or a concurrent map / sharding for scale. Guard every access path (including iteration and destruction), keep critical sections short and ordered, and regress with stress tests under TSan.
Atomics alone cannot fix multi-step map operations — the transaction boundary needs the mutex.
How do you expose C++ to Python (or another language)?
Answer
pybind11/nanobind for ergonomic bindings (automatic type conversions, GIL handling, NumPy support), C ABI plus extern "C" for stable cross-language boundaries, and narrow interfaces with value semantics to avoid lifetime traps across runtimes.
Keep ownership explicit at the boundary: who frees what, in which runtime, documented per function.
Example
// pybind11 sketch: // PYBIND11_MODULE(mine, m) { m.def("add", &add); }
How do you handle out-of-memory and allocation failure in C++?
Answer
Default new throws std::bad_alloc — let it propagate unless the layer can genuinely recover (drop caches, shed load, fail the request gracefully). nothrow new returns null for no-exception paths. Set new_handler for global policy, reserve emergency buffers for logging paths, and test OOM with fault injection rather than hope.
Most services: catch at request boundaries, count, shed load, keep serving.
Example
try { auto big = std::make_unique<char[]>(1ULL << 40); } catch (const std::bad_alloc&) { /* shed load, fail gracefully */ }
How do you review a C++ pull request? What do you check first?
Answer
Ownership and lifetimes first (who frees, any dangling, virtual destructor present), then const-correctness and references vs copies, then exceptions/edge paths, then algorithmic fit and naming. Mechanical checks (format, warnings-as-errors, sanitizers, tests) should already be green before human review starts.
A review that only debates style while missing a dangling reference has failed.
Key points
- 1Lifetimes — dangling, ownership, virtual destruction.
- 2Correctness — const, copies, edge cases, error paths.
- 3Design — algorithm choice, API shape, test coverage.
💡 Lifetimes before style is the reviewer credo worth stating out loud.
Recommended resourcesAffiliate links · may earn us a commission