Generic C Abstractions and C++ Smart-Pointer Lifetimes

Easy · Software Engineering Fundamentals · System Software Engineer · Technical Screen

Prompt

Low-level systems libraries need type-reusable containers and algorithms alongside deterministic, leak-free heap lifetime management. Compare how C idioms and modern C++ language facilities solve these two problems, supporting your explanation with short C and C++ code examples.

Section 1 — Type-Agnostic Programming in C

  1. Show how C writes reusable algorithms and containers through untyped data pointers (void *) paired with caller-supplied callback functions (as in libc qsort), alongside preprocessor container macros and C11 _Generic type dispatch. Provide a short C custom-comparator snippet.
  2. Explain at the compiler, object-file symbol table, and linker ABI level why C forbids defining multiple functions under the same identifier with different parameter types.
  3. Weigh untyped void * indirection against preprocessor-expanded inline generics across static type checking, CPU execution speed, compiled binary size, and debugging ergonomics.

Section 2 — Smart-Pointer Ownership in Modern C++

  1. Define RAII (Resource Acquisition Is Initialization), distinguish sole ownership (std::unique_ptr) from co-ownership (std::shared_ptr), and explain why std::unique_ptr disables copying and depends on move semantics.
  2. Describe the in-memory layout of std::shared_ptr, detailing the heap control block, strong versus weak reference counters, and the allocation difference between std::make_shared and passing a new pointer directly.
  3. Show how mutual std::shared_ptr links create memory-leaking cycles, how std::weak_ptr breaks those cycles, and how std::weak_ptr::lock safely promotes an observer when the target object might already be destroyed. Provide a concise C++ std::weak_ptr::lock snippet.

Scope & Expectations

  • Cover all six questions systematically across C generic mechanisms, linker symbol rules, and C++ smart-pointer ownership semantics.
  • Include working C and C++ code examples demonstrating overflow-safe qsort comparison and race-free std::weak_ptr::lock promotion.
  • Connect language rules to concrete machine-level trade-offs: unmangled vs. mangled symbols, indirect function calls vs. inlining, dual reference counters, and heap allocation layouts.

Step-by-step walkthrough

  1. Untyped pointers and callbacks in C (void* and qsort)

    C does not have templates, so its classic way to write one algorithm that works on any data type is type erasure: hiding the concrete element type behind an untyped memory address (void *) while asking the caller to supply the element's byte size and a callback (a pointer to a caller-written function that knows the real type).

    The standard library function qsort is the canonical example:

    void qsort(void *base, size_t nmemb, size_t size,
               int (*compar)(const void *, const void *));
    

    Because qsort only knows base (start address), nmemb (number of elements), and size (bytes per element), it treats the array as raw bytes. To reach element i, it computes (char *)base + i * size, and to swap two elements, it copies size bytes one chunk at a time:

    staff array of 3 structs (16 bytes each on 64-bit: 8B pointer + 4B int + 4B padding):
    
    byte offset:   0                16               32               48
                 +----------------+----------------+----------------+
       base ---> | {"Lin", 41}    | {"Ana", 29}    | {"Raj", 35}    |
                 +----------------+----------------+----------------+
                   element 0        element 1        element 2
                   base + 0*16      base + 1*16      base + 2*16
    

    Whenever qsort needs to know which of two elements comes first, it calls compar(elem_a, elem_b). Inside the callback, we cast the const void * pointers back to const struct employee *:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct employee {
        const char *name;
        int age;
    };
    
    static int compare_by_age(const void *pa, const void *pb) {
        const struct employee *a = (const struct employee *)pa;
        const struct employee *b = (const struct employee *)pb;
        /* Compare instead of subtracting (a->age - b->age), which overflows near INT_MIN. */
        return (a->age > b->age) - (a->age < b->age);
    }
    
    static int compare_by_name(const void *pa, const void *pb) {
        const struct employee *a = (const struct employee *)pa;
        const struct employee *b = (const struct employee *)pb;
        return strcmp(a->name, b->name);
    }
    
    int main(void) {
        struct employee staff[] = {{"Lin", 41}, {"Ana", 29}, {"Raj", 35}};
        size_t count = sizeof(staff) / sizeof(staff[0]);
    
        qsort(staff, count, sizeof(staff[0]), compare_by_age);  /* Ana 29, Raj 35, Lin 41 */
        qsort(staff, count, sizeof(staff[0]), compare_by_name); /* Ana 29, Lin 41, Raj 35 */
    
        for (size_t i = 0; i < count; i++) {
            printf("%s (%d)\n", staff[i].name, staff[i].age);
        }
        return 0;
    }
    

    Two practical details matter in systems code: - Never write return a->age - b->age; for arbitrary int values. If a->age is INT_MIN (-2147483648) and b->age is 1, the subtraction overflows a 32-bit signed integer (undefined behavior in C, wrapping to a positive number on two's-complement CPUs and reversing the sort order). (a->age > b->age) - (a->age < b->age) cleanly produces -1, 0, or +1. - No context pointer in ISO C qsort. Standard qsort cannot pass extra state (like ascending vs. descending) to compar without global/thread-local variables; POSIX.1-2024 standardized qsort_r to pass an extra void *arg context pointer.

  2. Preprocessor container generators and C11 _Generic

    The second C generic technique is macro metaprogramming: using #define preprocessor text substitution before compilation to stamp out separate, fully typed structs and static inline functions for each type you need.

    #include <stdint.h>
    #include <stdlib.h>
    
    #define DEFINE_VEC(T, NAME)                                          \
        typedef struct {                                                 \
            T *data;                                                     \
            size_t len;                                                  \
            size_t cap;                                                  \
        } NAME;                                                          \
                                                                         \
        static inline int NAME##_push(NAME *v, T value) {                \
            if (v->len == v->cap) {                                      \
                size_t new_cap = v->cap ? 2 * v->cap : 8;                \
                if (new_cap > SIZE_MAX / sizeof(T)) return -1;           \
                T *buf = (T *)realloc(v->data, new_cap * sizeof(T));     \
                if (buf == NULL) return -1;                              \
                v->data = buf;                                           \
                v->cap = new_cap;                                        \
            }                                                            \
            v->data[v->len++] = value;                                   \
            return 0;                                                    \
        }
    
    DEFINE_VEC(int, IntVec)       /* Generates struct IntVec and IntVec_push(IntVec *, int)       */
    DEFINE_VEC(double, DoubleVec) /* Generates struct DoubleVec and DoubleVec_push(DoubleVec *, double) */
    
    /* IntVec_push(&my_ints, "hello"); -> compile-time type error! */
    

    Here ## is the preprocessor token-pasting operator, turning NAME##_push into IntVec_push. Because the compiler sees real int * and double * types after preprocessing, it type-checks every call and can inline IntVec_push right into the caller.

    C11 also added _Generic, a compile-time type-selection expression that inspects the static type of an expression (without evaluating it) and picks the matching branch:

    #include <stdio.h>
    
    static void print_int(int x)         { printf("int: %d\n", x); }
    static void print_double(double x)   { printf("double: %g\n", x); }
    static void print_str(const char *s) { printf("string: %s\n", s); }
    
    /* String literals in C decay to char *, so map both char * and const char *. */
    #define print_value(x) _Generic((x),   \
        int:          print_int,           \
        double:       print_double,        \
        char *:       print_str,           \
        const char *: print_str            \
    )(x)
    
    /* print_value(42) -> int: 42;  print_value(3.5) -> double: 3.5;  print_value("hi") -> string: hi */
    

    Notice that (x) inside _Generic((x), ...) is only inspected for its type—only the trailing (x) runs at runtime, so print_value(i++) increments i just once. Still, _Generic is only compile-time dispatch over already-existing functions (print_int, print_double, print_str), each of which must have its own distinct C name.

  3. Object symbols, ABIs, and why C omits function overloading

    To understand why C forbids two functions named max(int, int) and max(double, double), look at how the compiler and linker (the tool that stitches compiled .o object files together) identify functions through symbols (the string names stored in an object file's symbol table) and the ABI (Application Binary Interface, the low-level binary rules for function names, register usage, and struct layouts):

    Source declaration          C object symbol (ELF)    C++ mangled symbol (Itanium ABI)
    ------------------------    ---------------------    --------------------------------
    int max(int, int)           max                      _Z3maxii   ("3-char name 'max', int, int")
    double max(double, double)  max  <-- COLLISION!      _Z3maxdd   ("3-char name 'max', double, double")
    
    • Direct symbol mapping in C: A C compiler emits the function's plain identifier as its external symbol (max on Linux ELF; _max with a single leading underscore on macOS Mach-O). Parameter types are not encoded in the symbol at all. Defining two max functions produces two identical max symbols, causing a duplicate-symbol linker error.
    • Name mangling in C++: C++ compilers support overloading via name mangling—encoding the function's namespace, class, and parameter types into a unique linker symbol (_Z3maxii vs. _Z3maxdd on GCC/Clang's Itanium ABI; MSVC uses a different mangling format, which is one reason MSVC and GCC C++ binaries cannot link directly).
    • Why C intentionally kept unmangled symbols:
      1. Universal ABI interoperability: Because C's symbol rule is trivial and standardized per OS/CPU, C is the universal foreign-function interface (FFI) across languages. Python's ctypes, Rust's extern "C", Go's cgo, assembly routines, and OS system libraries look up functions by their plain C name. Even C++ uses extern "C" to disable name mangling when exposing C-compatible APIs (which immediately disables overloading on those functions).
      2. Historical toolchain limits and ABI stability: Early C linkers (C89) only guaranteed 6 significant characters in external identifiers, leaving no room for encoded parameter lists, and changing symbol naming later would have broken decades of compiled shared libraries.
  4. Comparing void* indirection against preprocessor inline generics

    Choosing between void * type erasure and macro-instantiated generics trades binary compactness and clean ABI boundaries against compile-time safety and CPU speed:

    Dimension          void* + function callbacks            Macro-expanded inline generics
    -----------------  ------------------------------------  ------------------------------------
    Type safety        None at compile time: wrong sizeof    Full static type checking on every
                       or wrong cast silently corrupts RAM   element read, write, and comparison
    Runtime speed      Slower: indirect call per step +      Faster: direct typed loads/stores;
                       generic runtime-sized byte copies     compiler inlines and SIMD-vectorizes
    Memory layout      Often stores void* pointers (extra    Contiguous flat array of T values
                       heap allocations + cache misses)      with strong spatial cache locality
    Binary code size   1 shared compiled function total      1 copy per type T ("code bloat")
    Debugging & IDEs   Normal C stack traces and breakpoints Compiler errors and step-debugger
                                                             point to a single macro call line
    Library ABI        Ships cleanly in a compiled .so/.dll  Must ship as source code in headers
    Macro pitfalls     None                                  Double evaluation in naive macros
                                                             (MAX(i++, j)) and name collisions
    

    Worked numeric example for performance: Sorting n = 1,000,000 32-bit integers takes roughly n * log2(n) ≈ 20,000,000 comparisons. With qsort, every comparison makes an indirect call through a function pointer that the compiler usually cannot inline across library boundaries, plus byte-wise swaps of runtime length size = 4. With a macro-generated sort_int (or C++ std::sort), a < b compiles to a single register compare instruction with zero call overhead, often running 2x–5x faster on primitive types.

    In large C codebases (such as OS kernels and storage engines), engineers often combine both: write one compiled void * engine for heavy logic to avoid code bloat (binary size growth from duplicating machine code per type), and wrap it in tiny static inline typed helper functions or macros so callers still get compile-time type checking.

  5. RAII, unique_ptr vs. shared_ptr, and why unique_ptr needs move semantics

    RAII (Resource Acquisition Is Initialization) is C++'s core resource-management idiom: tie every resource (heap memory, open file, socket, mutex lock) to a local stack-based object whose constructor acquires the resource and whose destructor releases it. Because C++ guarantees that local destructors run whenever execution leaves a scope—whether through the closing }, an early return, break, or stack unwinding during a caught exception—cleanup cannot be accidentally skipped.

    Modern C++ expresses heap ownership directly in pointer types: - std::unique_ptr<T> (exclusive ownership): Exactly one unique_ptr owns the T object at any moment. When that unique_ptr is destroyed or reset, it deletes the T. With the default deleter, sizeof(std::unique_ptr<T>) is 8 bytes on 64-bit platforms (identical to a raw T *) with zero atomic or heap overhead. - std::shared_ptr<T> (shared ownership): Multiple shared_ptr instances co-own the same T object. Copying increments an atomic reference count; destroying decrements it, and the last owner to reach count 0 deletes the T.

    Why move semantics are mandatory for std::unique_ptr: Suppose unique_ptr allowed ordinary copying (b = a). Both a and b would hold the same raw pointer 0x5000. When b left scope its destructor would delete 0x5000, and when a left scope its destructor would delete 0x5000 a second time—a double free (heap corruption / undefined behavior). Therefore, unique_ptr explicitly deletes its copy constructor and copy-assignment operator (= delete). To pass ownership safely out of a factory function, into a "sink" function, or inside a resizing std::vector, unique_ptr relies on move semantics: transferring the raw pointer into the destination unique_ptr while setting the source unique_ptr to nullptr, preserving the "at most one owner" invariant at every step.

    #include <cstddef>
    #include <memory>
    #include <utility>
    #include <vector>
    
    struct Buffer {
        std::vector<char> data;
        explicit Buffer(std::size_t bytes) : data(bytes) {}
    };
    
    std::unique_ptr<Buffer> create_buffer(std::size_t bytes) {
        return std::make_unique<Buffer>(bytes);   // Ownership moves out to caller
    }
    
    void sink_buffer(std::unique_ptr<Buffer> buf) {
        // sink_buffer now exclusively owns *buf
    }   // buf goes out of scope here -> ~Buffer() runs automatically
    
    int main() {
        std::unique_ptr<Buffer> p1 = create_buffer(4096);
        // std::unique_ptr<Buffer> bad = p1;               // Compile error: copy is deleted!
        std::unique_ptr<Buffer> p2 = std::move(p1);        // p1 becomes nullptr; p2 owns Buffer
        sink_buffer(std::move(p2));                        // p2 becomes nullptr; Buffer freed
    
        std::shared_ptr<Buffer> s1 = std::make_shared<Buffer>(1024); // strong count = 1
        std::shared_ptr<Buffer> s2 = s1;                             // strong count = 2
    }   // s2 destroyed (count 2 -> 1), then s1 destroyed (count 1 -> 0 -> Buffer freed)
    
  6. Inside std::shared_ptr: control blocks, dual counters, and make_shared

    On 64-bit platforms, a std::shared_ptr<T> object is 16 bytes (two 8-byte pointers): 1. A direct pointer to the T object (for fast *p and p-> access without extra indirection). 2. A pointer to a heap-allocated control block—a shared bookkeeping record that tracks the object's lifetime across all owners and observers.

    Inside the control block live: - Strong reference count (use_count()): Number of active std::shared_ptr instances co-owning the T. When the strong count drops to 0, the T object's destructor runs immediately. - Weak reference count: Number of active std::weak_ptr observers pointing at this control block. The control block's own memory cannot be freed until both the strong count and the weak count reach 0, so a weak_ptr can always safely inspect the control block to ask whether the T has already expired. - Type-erased deleter and allocator (when custom ones are supplied).

    Compare the two ways of constructing a shared_ptr:

    1) std::shared_ptr<Widget> p(new Widget());   --> 2 separate heap allocations:
    
       shared_ptr p (16B on stack)         Heap block #1              Heap block #2
       +-------------+-------------+       +------------------+       +--------------------+
       | T* ptr      | ctrl*       | ----> | Widget object    |       | Control Block      |
       +------|------+------|------+       +------------------+       | strong = 1         |
              +-------------+---------------------------------------> | weak   = 0         |
                    (points to #1; ctrl* points to #2)                | deleter/allocator  |
                                                                      +--------------------+
    
    2) auto p = std::make_shared<Widget>();       --> 1 combined heap allocation:
    
       shared_ptr p (16B on stack)         Single contiguous heap block
       +-------------+-------------+       +--------------------+------------------+
       | T* ptr      | ctrl*       | ----> | Control Block      | Widget storage   |
       +-------------+-------------+       | strong=1, weak=0   | (in-place)       |
                                           +--------------------+------------------+
    
    • std::make_shared<T>(...) advantages: Performs 1 heap allocation instead of 2 (halving allocator overhead) and places the control block directly adjacent to T in memory, improving CPU cache locality.
    • std::make_shared<T>(...) trade-offs: Because the control block and T live in a single malloc block, if strong drops to 0 (~T() runs) while a long-lived weak_ptr still holds weak > 0, the raw memory for T cannot be returned to the heap allocator until the last weak_ptr is also destroyed. Also, make_shared cannot accept a custom deleter (which requires the shared_ptr(ptr, deleter) constructor).
    • Thread-safety note: Control-block reference-count updates use atomic instructions, so copying/destroying separate shared_ptr variables pointing to the same T across threads is safe, but reading/mutating the T object itself (or mutating the same shared_ptr instance from two threads without synchronization) still requires a lock or std::atomic<std::shared_ptr<T>>.
  7. Breaking reference cycles safely with std::weak_ptr::lock()

    Why cyclic shared_ptr references leak: Reference counting has no cycle detector. If a Parent holds a shared_ptr<Child> and that Child holds a shared_ptr<Parent>, each object keeps the other's strong count at >= 1 even after all outside variables go out of scope:

    Cycle with two shared_ptrs (LEAK):            Cycle broken with weak_ptr (CLEAN):
      local root -> [Parent strong=2]               local root -> [Parent strong=1, weak=1]
                      |           ^                                 |                :
           shared_ptr |           | shared_ptr           shared_ptr |                : weak_ptr
                      v           |                                 v                :
                    [Child  strong=1]                             [Child  strong=1]..:
    
    When local root leaves scope:                 When local root leaves scope:
      Parent strong: 2 -> 1 (still > 0, leaks!)     Parent strong: 1 -> 0 (~Parent runs!)
      Child  strong: 1      (never freed!)          ~Parent destroys children -> Child strong: 1 -> 0!
    

    How std::weak_ptr breaks cycles: Model ownership as a tree or directed acyclic graph (DAG) where parent-to-child owning edges use std::shared_ptr and back-pointers, caches, or observer lists use std::weak_ptr (a non-owning observer that increments only the control block's weak count, leaving the strong count untouched).

    How std::weak_ptr::lock() safely accesses the object: Because the target object can be destroyed on another thread at any moment, weak_ptr provides no * or -> operator. Instead, you call w.lock(), which performs an atomic compare-and-swap check on the control block: - If strong_count > 0, it atomically increments strong_count and returns a new owning std::shared_ptr<T> that guarantees the object stays alive for the duration of your local scope. - If strong_count == 0, it returns an empty std::shared_ptr<T> (nullptr).

    #include <iostream>
    #include <memory>
    #include <string>
    #include <utility>
    #include <vector>
    
    struct Node {
        std::string name;
        std::vector<std::shared_ptr<Node>> children; // Owning edges: Parent -> Child
        std::weak_ptr<Node> parent;                  // Non-owning back-edge: breaks cycle
    
        explicit Node(std::string label) : name(std::move(label)) {}
        ~Node() { std::cout << "Destroyed " << name << "\n"; }
    };
    
    void print_parent(const Node& child) {
        // lock() atomically checks liveness AND acquires temporary shared ownership.
        if (std::shared_ptr<Node> pinned_parent = child.parent.lock()) {
            std::cout << child.name << "'s parent is " << pinned_parent->name << "\n";
        } else {
            std::cout << child.name << "'s parent has already expired\n";
        }
    }
    
    int main() {
        auto root = std::make_shared<Node>("root"); // root strong = 1
        auto leaf = std::make_shared<Node>("leaf"); // leaf strong = 1
    
        root->children.push_back(leaf);             // leaf strong = 2
        leaf->parent = root;                        // root strong stays 1 (weak observer added)
    
        print_parent(*leaf);                        // Prints: leaf's parent is root
        root.reset();                               // root strong 1 -> 0 ("Destroyed root");
                                                    // leaf strong 2 -> 1 (still held by local 'leaf')
        print_parent(*leaf);                        // Prints: leaf's parent has already expired
    }                                               // leaf strong 1 -> 0 ("Destroyed leaf")
    

    Never write if (!w.expired()) { auto p = w.lock(); p->... }: in multithreaded code, another thread can drop the last shared_ptr right between expired() and lock()—a TOCTOU (time-of-check to time-of-use) race condition—making p null and crashing on p->. Calling lock() once and testing the returned shared_ptr is completely race-free.

Intuition & how it works

Think of generic programming in C as two ways a warehouse can handle packages of different shapes, and C++ smart pointers as legal property deeds enforced by the compiler: - In C, either the warehouse treats every item as an unlabeled box of size bytes with a sticky note pointing to an instruction manual (void * plus a function-pointer callback like qsort), or you use a rubber stamp before compiling to print a custom-fitted shelf for integers and another for floats (#define macro containers and C11 _Generic). - In C++, RAII (Resource Acquisition Is Initialization—tying a resource's lifetime to a stack object whose destructor automatically cleans it up when scope exits) turns raw pointers into explicit ownership deeds: std::unique_ptr is a single car title that can only be signed over via std::move and never photocopied, while std::shared_ptr is a co-owned deed backed by a shared ledger (the control block, a small heap structure storing atomic reference counts), with std::weak_ptr acting as a visitor pass that checks whether the building still stands before stepping inside.

Naive approaches break down quickly in systems code. In C, manually casting void * erases static types, so passing the wrong sizeof or wrong comparator compiles cleanly and silently corrupts memory, while calling free() by hand leaks memory whenever an early return or exception bypasses cleanup. In C++, naively linking two structs back-to-back with std::shared_ptr creates a reference cycle whose counts never hit zero, leaking both objects permanently.

Walk through two tiny concrete examples to see both mechanisms in action: 1. C qsort on 3 employee structs (16 bytes each, 48 bytes total): qsort receives base, nmemb = 3, and size = 16. It steps through memory at base + 0, base + 16, and base + 32, calling compare_by_age(pa, pb) to compare ages (41, 29, 35) and swapping 16-byte blocks until [Ana 29, Raj 35, Lin 41] are ordered—without qsort ever knowing struct employee exists. 2. C++ shared_ptr + weak_ptr on 2 tree nodes (root and leaf): root->children holds a shared_ptr to leaf (leaf strong count = 2), while leaf->parent holds a weak_ptr to root (root strong count stays 1, weak count = 1). Calling root.reset() drops root's strong count 1 -> 0, immediately destroying root and dropping leaf's strong count 2 -> 1; calling leaf->parent.lock() then atomically sees strong count 0 and safely returns an empty shared_ptr instead of a dangling pointer.

Key points

  • Two flavors of C generics: Type erasure (hiding concrete types behind void *, runtime byte sizes, and function-pointer callbacks) compiles a single shared implementation at the cost of zero static type safety and indirect call overhead; macro instantiation (#define container generators and C11 _Generic, a compile-time expression-type selector) produces type-checked, inlinable code at the cost of code bloat (duplicate machine code per type) and harder macro debugging.
  • Why C lacks function overloading: A C ABI (Application Binary Interface—the binary calling and naming convention between object files) maps a function directly to its plain symbol name (max), so overloaded parameter lists would collide at link time. C++ enables overloading through name mangling (encoding parameter types into symbols such as _Z3maxii vs. _Z3maxdd), while C preserves unmangled names so every OS kernel and language FFI (extern "C", Rust, Python, Go) can link effortlessly.
  • Exclusive vs. shared ownership via RAII: std::unique_ptr<T> enforces single ownership by deleting copy operations and requiring move semantics (transferring the pointer and nulling the source so two destructors can never double-free the same address), keeping the size of a single raw pointer (8 bytes on 64-bit) with default deleters. std::shared_ptr<T> (16 bytes: stored T * + control-block pointer) shares ownership via atomic reference updates.
  • Two counters inside the shared_ptr control block: The strong count governs object lifetime (strong -> 0 runs ~T()), whereas the weak count governs control-block memory lifetime (strong == 0 and weak -> 0 frees the control block).
  • Breaking cycles safely with std::weak_ptr::lock(): Replacing back-edges (child -> parent) with weak_ptr prevents strong-count cycles, and w.lock() uses an atomic compare-and-swap operation to return either a valid owning shared_ptr or nullptr in one thread-safe step.

Common mistakes

  • Subtracting integers inside a C qsort comparator (return a - b;): Subtracting 1 from INT_MIN overflows signed int (undefined behavior in C and wrong sort sign on two's-complement hardware); use (a > b) - (a < b) instead.
  • Confusing C11 _Generic with true function overloading: _Generic only routes an expression at compile time to differently named C functions inside a macro; C still cannot emit two functions with the same linker symbol.
  • Evaluating macro arguments multiple times: Naive expression macros like #define MAX(a, b) ((a) > (b) ? (a) : (b)) evaluate MAX(i++, j) twice; prefer static inline functions generated by a macro when type-specific bodies are needed.
  • Constructing two std::shared_ptrs from the same raw pointer (shared_ptr<T> a(raw), b(raw);): That allocates two independent control blocks with strong count 1 each, causing a double free; always construct once with std::make_shared (or use std::enable_shared_from_this inside methods) and copy the shared_ptr.
  • Checking if (!w.expired()) before w.lock(): In multithreaded code, another thread can destroy the last shared_ptr between the two calls—a TOCTOU (time-of-check to time-of-use) race condition—leaving w.lock() null; always call if (auto p = w.lock()) once.
  • Assuming std::shared_ptr makes the pointed-to T thread-safe: Only the control block's reference counts are atomic; concurrent mutations to T's fields still require synchronization.

Follow-up questions

  • How does constructing a std::shared_ptr with std::make_shared compare against wrapping a new pointer in terms of heap allocations, cache behavior, and memory reclamation? Wrapping a new pointer (std::shared_ptr<T>(new T())) performs two separate heap allocations—one for T and a second for the control block—paying allocator bookkeeping twice and often placing the reference counts and T's fields on distant CPU cache lines. std::make_shared<T>() allocates one contiguous memory block holding [control block | T] side by side, cutting heap allocations in half and keeping counts and data warm in neighboring cache lines. The trade-off is that make_shared cannot take a custom deleter, and if a long-lived std::weak_ptr outlives all shared_ptrs, ~T() runs immediately when the strong count hits 0 while the combined heap block's raw memory stays reserved until the weak count also hits 0.
  • Why does a custom deleter affect sizeof(std::unique_ptr) and its static type, whereas std::shared_ptr keeps a fixed size and type regardless of deleter? In std::unique_ptr<T, D>, the deleter type D is encoded directly in the template type and stored inline inside the unique_ptr via empty base optimization (a compiler layout rule allowing stateless types like default deleters or captureless lambdas to occupy 0 extra bytes), keeping unique_ptr at 8 bytes with an inlined cleanup call—whereas a function-pointer deleter grows sizeof to 16 bytes and prevents mixing differently-deleted unique_ptrs in one std::vector. In std::shared_ptr<T>, any custom deleter is type-erased (stored inside the heap control block behind a virtual dispatch hook) rather than part of the template signature, so every shared_ptr<T> remains 16 bytes and shares the exact same static type at the cost of control-block heap storage and one indirect call on destruction.
  • How would you build an intrusive reference-counting mechanism in plain C, including the embedded struct layout and atomic retain/release functions? An intrusive reference count embeds the atomic counter and cleanup callback directly inside the managed struct itself (needing just 1 allocation and no separate control block, like the Linux kernel's struct kref). Embed a struct refcount field inside your object, initialize refs to 1 on creation, increment with memory_order_relaxed in ref_retain (safe because the caller already holds a live reference), and decrement with memory_order_acq_rel in ref_release so all prior writes across threads are visible before invoking destroy when the old count was 1. Inside destroy, recover the enclosing struct pointer via offsetof and free it:
#include <stdatomic.h>
#include <stddef.h>
#include <stdlib.h>

struct refcount {
    atomic_size_t refs;
    void (*destroy)(struct refcount *rc);
};

static inline void ref_init(struct refcount *rc, void (*destroy)(struct refcount *)) {
    atomic_init(&rc->refs, 1);  /* Creator starts with 1 owning reference */
    rc->destroy = destroy;
}

static inline void ref_retain(struct refcount *rc) {
    atomic_fetch_add_explicit(&rc->refs, 1, memory_order_relaxed);
}

static inline void ref_release(struct refcount *rc) {
    if (atomic_fetch_sub_explicit(&rc->refs, 1, memory_order_acq_rel) == 1) {
        rc->destroy(rc);        /* Last owner frees the enclosing struct */
    }
}

/* Example usage: recover enclosing struct buffer via offsetof */
struct buffer {
    struct refcount rc;
    size_t len;
    unsigned char data[];
};

static void buffer_destroy(struct refcount *rc) {
    struct buffer *buf = (struct buffer *)((char *)rc - offsetof(struct buffer, rc));
    free(buf);
}

Follow-up questions

Similar questions

More Netapp interview questions

All 9 Netapp questions →