What is the C++ memory model and atomic operations?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized C++ deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
The C++ memory model (C++11) formally defines how threads interact with shared memory — establishing rules for when writes by one thread become visible to other threads. Memory ordering options (from relaxed to strict): std::memory_order_relaxed — no ordering constraints, only atomicity (fastest — for counters that don't need synchronization guarantees); std::memory_order_acquire — all reads/writes after this point are NOT moved before this operation (load barrier); std::memory_order_release — all reads/writes before this point are NOT moved after this operation (store barrier); std::memory_order_acq_rel — both acquire and release; std::memory_order_seq_cst — total sequential consistency (default — safest, most expensive). std::atomic examples: std::atomic<int> count{0}; // Simple counter (relaxed OK): count.fetch_add(1, std::memory_order_relaxed); // Publish data pattern (producer): std::atomic<bool> ready{false}; data = compute(); // Prepare data ready.store(true, std::memory_order_release); // Consume data pattern (consumer): while (!ready.load(std::memory_order_acquire)); // Spin until ready use(data); // Safe -- guaranteed to see compute() result // Compare-and-swap (lock-free algorithms): int expected = 0; count.compare_exchange_strong(expected, 1); // Atomic: if count==0, set to 1. Lock-free data structures: use compare_exchange_weak/strong loops to build lock-free stacks, queues. Avoid ABA problem with versioned pointers. std::memory_order_relaxed use case: std::atomic<int> hitCount{0}; hitCount.fetch_add(1, std::memory_order_relaxed); // Cache stats -- order doesn't matter. Happens-before relationship: if thread A does a release store and thread B does an acquire load of the same atomic, all operations before A's store are visible after B's load.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.