Pick a topic — languages & databases — 100+ questions and answers in the center column.
C++
OOP, RAII, STL, move semantics, modern C++.
102 questions
Question 1
Multi-paradigm extension of C with classes, templates, RAII, exceptions, and a large standard library—backward compatible-ish with C.
Example code
#include <iostream>
int main() { std::cout << "C++\n"; }Question 2
Resource Acquisition Is Initialization: constructors acquire, destructors release—ties lifetimes to scopes for leaks safety.
Example code
class File { int fd; public: File(int f):fd(f){} ~File(){ /* close */ } };Question 3
If you manage raw resources, define copy/move/dtor appropriately—or prefer smart pointers/containers for rule of zero.
Example code
class R { int* p; public: R(int x):p(new int(x)){} ~R(){delete p;} R(const R&)=delete; R& operator=(const R&)=delete; };Question 4
unique_ptr exclusive ownership; shared_ptr refcounted; weak_ptr breaks cycles—prefer unique_ptr by default.
Example code
#include <memory>
auto u = std::make_unique<int>(3);Question 5
~T() runs on scope exit, delete, or exception unwind—must not throw; virtual dtor if polymorphic delete through base.
Example code
struct B { virtual ~B()=default; };Question 6
Dynamic dispatch via vtable; override in derived; pure virtual = 0 makes class abstract.
Example code
struct D : B { void f() override {} };Question 7
Indirection and inhibited devirtualization vs CRTP/static polymorphism—trade clarity vs performance.
Example code
// virtual calls: *(void***)obj is vptr; indirect jump through vtableQuestion 8
Initialize bases and members before body runs—required for const, references, base classes without default ctor.
Example code
struct Q { int a, b; Q(): a(1), b(2) {} }; // ctor initializer listQuestion 9
Prevent implicit conversions from single-argument constructors—reduce surprise overload resolutions.
Example code
struct E { explicit E(int) {} }; // E x = 1; would not compileQuestion 10
Copy duplicates resources; move transfers ownership leaving source in valid unspecified state—move enables cheap returns.
Example code
std::vector<int> v{1,2,3};Question 11
Casts to rvalue reference to enable move overloads—doesn't move by itself; name is misleading for beginners.
Example code
explicit S(int){}Question 12
lvalue has identity; rvalue often temporary; xvalues from std::move; drives overload resolution and move semantics.
Example code
std::string a = "hi";
std::string b = std::move(a);Question 13
std::forward with universal references preserves value category in templates—used in wrappers like make_unique.
Example code
int x = 0;
int&& r = std::move(x);Question 14
Compile-time polymorphism; code bloat risk; SFINAE, concepts (C++20) constrain overload sets.
Example code
auto id = [](auto x) { return x; };Question 15
Named requirements on template parameters—clearer errors than SFINAE tricks.
Example code
template<typename T> T twice(T x){ return x+x; }Question 16
Type deduction reduces verbosity; decltype(auto) preserves references—watch dangling with auto&& to temporaries.
Example code
template<std::integral T> T abs(T x){ return x<0?-x:x; }Question 17
Uses begin/end; beware invalidation while mutating containers being iterated.
Example code
auto x = 1; decltype(x) y = 2;Question 18
Amortized constant push_back; reserve when size known; iterator invalidation rules on reallocation.
Example code
for (int n : v) std::cout << n;Question 19
SSO on many libs; contiguous data since C++11; pass string_view (C++17) to avoid copies in read-only APIs.
Example code
std::vector<int> v; v.reserve(100); v.push_back(1);Question 20
Non-owning reference—must not point to freed temporaries; classic footgun crossing async boundaries.
Example code
std::string_view sv = "abc";Question 21
Fixed stack size vs dynamic heap; array keeps size in type for cheap stack buffers.
Example code
std::array<int,3> a{1,2,3};Question 22
Balanced tree vs hash table—ordering vs average O(1); define hash for custom keys in unordered.
Example code
std::map<std::string,int> m{{"a",1}};Question 23
input/output/forward/bidirectional/random access—algorithms require minimum category.
Example code
std::unordered_map<std::string,int> h;Question 24
Prefer standard algorithms over raw loops for clarity—know complexity and iterator requirements.
Example code
std::sort(v.begin(), v.end());Question 25
Closure objects; capture by value/reference; mutable lambdas; generic lambdas auto params (C++14).
Example code
auto lam = [x=1](int y){ return x+y; };Question 26
stack unwinding calls destructors; noexcept affects move in vectors; don't throw from dtor.
Example code
try { throw 1; } catch(int e) { }Question 27
Basic, strong, noexcept—document for containers and transactional operations.
Example code
S operator+(S a, S b){ return {}; }Question 28
Make meaning obvious; preserve expectations; free functions for symmetry (e.g. operator<<).
Example code
class F { friend std::ostream& operator<<(std::ostream&, const F&); };Question 29
Grants access to private members—breaks encapsulation minimally; sometimes needed for operators.
Example code
struct D : B1, B2 {};Question 30
Diamond problem—virtual inheritance mitigates; prefer composition or interfaces.
Example code
template<class D> struct B { void f(){ static_cast<D*>(this)->impl(); } };Question 31
Curiously Recurring Template Pattern for static polymorphism—no virtual cost; harder to read.
Example code
std::jthread t([]{ std::cout<<"run\n"; });Question 32
Join or detach—destructor std::terminate if still joinable; prefer RAII wrapper or jthread (C++20).
Example code
std::mutex m; { std::lock_guard g(m); /* ... */ }Question 33
RAII lock; use unique_lock when need to unlock mid-scope or with condition_variable.
Example code
std::condition_variable cv; std::unique_lock lk(m); cv.wait(lk, pred);Question 34
Wait with predicate loop to handle spurious wakeups; avoid lost signals.
Example code
std::atomic<int> a{0}; a.fetch_add(1, std::memory_order_relaxed);Question 35
Relaxed/acquire/release for lock-free structures—expert territory; data races are UB.
Example code
auto fut = std::async(std::launch::async, []{ return 1; });Question 36
Launch policy async vs deferred unclear—often prefer packaged_task and explicit threads for control.
Example code
constexpr int sq(int x){ return x*x; }Question 37
Compile-time evaluation when possible—C++20 consteval for must-compile-time.
Example code
inline namespace v2 { void api(); }Question 38
ABI versioning and ADL tricks—library evolution pattern.
Example code
namespace N { struct X{}; void swap(X&,X&); }Question 39
Unqualified calls also search namespaces of argument types—enables swap idioms and operators.
Example code
template<class T> std::enable_if_t<std::is_integral_v<T>,T> f(T x){return x;}Question 40
Substitution Failure Is Not An Error—enables enable_if tricks before concepts.
Example code
std::optional<int> o = 3;
if (o) std::cout << *o;Question 41
Represents absent value without sentinel; no unexpected null like pointers—watch value() vs value_or.
Example code
std::variant<int,std::string> v = "hi";
std::visit([](auto&& x){ std::cout << x; }, v);Question 42
Type-safe union; visit pattern for dispatch—bad_variant_access if wrong state.
Example code
std::any a = 1;
std::cout << std::any_cast<int>(a);Question 43
Type-erased single value—runtime type checks; performance cost vs templates.
Example code
std::vector<int> v{1,2,3};
std::span<int> s{v};Question 44
Non-owning contiguous view—bounds-safe-ish API for arrays/vectors in C++20.
Example code
std::cout << std::format("x={}", 1);Question 45
Type-safe formatting replacing printf/iostreams ergonomics—C++20 feature adoption growing.
Example code
std::jthread t([]{ });Question 46
Joining thread with stop_token cooperative cancellation—C++20 improves thread RAII.
Example code
std::latch l(1); l.count_down(); l.wait();Question 47
Coordination primitives for parallel algorithms—know differences vs counting semaphores.
Example code
auto p = std::filesystem::path("a/b");Question 48
Portable path operations—exceptions vs error_code overloads for robust tools.
Example code
auto t0 = std::chrono::steady_clock::now();Question 49
Durations and clocks—avoid mixing clock types; use steady_clock for intervals.
Example code
std::mt19937 g(std::random_device{}());
std::uniform_int_distribution<int> d(1,6);Question 50
Proper RNG engines and distributions—rand() discouraged for quality randomness.
Example code
std::regex r("\\d+");
std::smatch m; std::regex_search("a1", m, r);Question 51
Convenient but can be slow—consider RE2 for untrusted patterns to avoid catastrophic backtracking.
Example code
// prefer {fmt} or std::formatQuestion 52
iostreams type-safe but heavy compile; fmt/format faster compile and clearer errors.
Example code
static_assert(std::is_trivially_copyable_v<int>);Question 53
Legacy terminology evolved—trivially copyable matters for memcpy/memset legality.
Example code
auto p = new(std::align_val_t{64}) T();Question 54
Over-aligned types may need aligned new/delete—placement new alignment rules.
Example code
int* p = new int(1); delete p;Question 55
new calls constructors; malloc raw bytes—mixing delete on malloc is UB.
Example code
alignas(T) unsigned char buf[sizeof(T)];
T* t = new (buf) T(); t->~T();Question 56
Construct object in preallocated storage—must manually call destructor.
Example code
std::vector<std::unique_ptr<B>> items;Question 57
vector<unique_ptr<T>> manages polymorphic objects—clone patterns if copying needed.
Example code
struct B { virtual ~B()=default; };Question 58
Base class polymorphic use requires virtual ~Base to delete derived via base pointer.
Example code
D d; B b = d; // slicesQuestion 59
Assigning derived to base by value truncates—use pointers or references for polymorphism.
Example code
std::vector<std::unique_ptr<B>> v;Question 60
vector<Base> stores bases only—use vector<unique_ptr<Base>> for polymorphic collections.
Example code
std::function<int(int)> f = [](int x){ return x; };Question 61
Type erasure and possible heap allocation—hot paths may prefer templates.
Example code
auto g = [](int a,int b){ return a+b; };Question 62
Lambdas clearer and often faster—bind mostly legacy style.
Example code
template<class...A> Wrapper(A&&...a):t(std::forward<A>(a)...){}Question 63
Forwarding references compete with copy ctor—enable_if/disable_if patterns historically.
Example code
struct B { explicit operator bool() const { return true; } };Question 64
operator bool explicit avoids implicit conversion surprises.
Example code
enum class E { A, B };Question 65
Scoped strongly typed enums—prefer over plain enum for new code.
Example code
using enum E;Question 66
C++20 brings enum members into scope locally—reduces verbosity carefully.
Example code
auto [x,y] = std::pair{1,2};Question 67
Decompose tuple/pair/struct members—clean iteration over map entries.
Example code
if (auto it = m.find(k); it != m.end()) {}Question 68
C++17 limit scope of init variables in condition—safer than outer declarations.
Example code
std::byte b{0x01};Question 69
Distinct byte type for memory buffers—avoid char/unsigned char ambiguity for bits.
Example code
char buf[32]; auto r = std::to_chars(buf, buf+32, 12345);Question 70
Fast locale-independent number parsing/formatting—preferred in hot paths.
Example code
std::vector<bool> vb{true,false};Question 71
Packed bits—not a true container of bool references—gotcha for templates expecting T&.
Example code
std::string s = "hi";Question 72
std::string keeps short strings internal—iterators may invalidate less obviously.
Example code
v.push_back(maybe_realloc);Question 73
Insert/erase may invalidate all iterators—use indexes or careful algorithms.
Example code
// iterators may invalidate on insert middleQuestion 74
More complex than vector—middle insert invalidates more than ends in implementations.
Example code
std::list<int> a{1}, b{2}; a.splice(a.end(), b);Question 75
O(1) move nodes between lists—no element copy if node-based ownership moved.
Example code
std::priority_queue<int> pq; pq.push(3); pq.push(1);Question 76
Heap via underlying container—know no efficient update; often use custom heaps for Dijkstra.
Example code
struct H { size_t operator()(const std::string& s) const noexcept { return std::hash<std::string>{}(s); } };Question 77
Poor hash enables attacker collisions—secure_hash or randomized seed for untrusted keys.
Example code
std::vector<int, MyAlloc<int>> v;Question 78
STL containers accept allocators—game engines use pool allocators for fragmentation control.
Example code
std::pmr::monotonic_buffer_resource pool;Question 79
Polymorphic memory resources—arena allocators for parse trees and compilers.
Example code
auto p = std::make_shared<int>(1);Question 80
Separate allocation with make_shared merges object+control block—performance and exception safety win.
Example code
std::weak_ptr<int> w = p; if (auto s = w.lock()) {}Question 81
Break cycles in graphs; lock() to temporarily promote to shared_ptr safely.
Example code
struct S : std::enable_shared_from_this<S> { std::shared_ptr<S> me() { return shared_from_this(); } };Question 82
Get shared_ptr from this inside object—prevents double control blocks.
Example code
std::atomic<std::shared_ptr<int>> ap;Question 83
C++20 atomic<shared_ptr>—lock-free is complicated; often mutex simpler.
Example code
volatile int* reg = (int*)0x4000;Question 84
Not for thread synchronization—use atomics; volatile for hardware registers only.
Example code
std::atomic_thread_fence(std::memory_order_seq_cst);Question 85
std::atomic_thread_fence rare—prefer atomic operations with correct orders.
Example code
std::scoped_lock lk(m1, m2);Question 86
Global lock order prevents deadlocks—document and enforce across modules.
Example code
std::try_lock(m1, m2);Question 87
std::try_lock on multiple mutexes—backoff pattern to avoid deadlock.
Example code
thread_local int x;Question 88
thread_local keyword—per-thread globals; initialization rules per implementation.
Example code
std::once_flag f; std::call_once(f, []{});Question 89
One-time initialization flag—singleton pattern without static initialization order fiasco pitfalls.
Example code
// construct on first useQuestion 90
Cross-TU static ctor order undefined—construct on first use idiom mitigates.
Example code
if constexpr (std::is_integral_v<T>) { }Question 91
Compile-time branch in templates—cleaner than SFINAE for many cases.
Example code
template<typename T> void g(){ if constexpr (sizeof(T)==4){} }Question 92
Discards non-taken branch—ODR and template instantiation rules still apply.
Example code
import std;Question 93
import std reduces compile times—tooling adoption still maturing in 2024-2026 era.
Example code
// co_await in coroutine bodyQuestion 94
co_await/co_yield stackless coroutines—compiler transforms; promise types complex.
Example code
auto v = std::views::iota(1,4);Question 95
Composable views; lazy evaluation—watch dangling if referencing temporaries in pipelines.
Example code
auto r = v | std::views::take(3);Question 96
filter/transform may reference expired temporaries—materialize when unsure.
Example code
template<std::integral T> void f(T x){}Question 97
syntax auto f(T t) requires std::integral<T>—clear constraints.
Example code
auto operator<=>(const S&) const = default;Question 98
Spaceship operator generates relational ops—= default for memberwise.
Example code
S() = default;Question 99
Explicitly default special members when needed for clarity or triviality guarantees.
Example code
static_assert(noexcept(S(std::move(s))));Question 100
Vectors move elements only if move ctor is noexcept—otherwise copies on reallocation in older standards nuances.
Example code
extern "C" void api(void);Question 101
Compiler flags and STL versions must match across DLL boundaries—export only C API or stable ABI types.
Example code
extern "C" int add(int a,int b);Question 102
Disable C++ name mangling for C linkage—required for cross-language APIs.
Example code
// cpp — add snippet 102