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
- Show how C writes reusable algorithms and containers through untyped data pointers (
void *) paired with caller-supplied callback functions (as in libcqsort), alongside preprocessor container macros and C11_Generictype dispatch. Provide a short C custom-comparator snippet. - 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.
- 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++
- Define RAII (Resource Acquisition Is Initialization), distinguish sole ownership (
std::unique_ptr) from co-ownership (std::shared_ptr), and explain whystd::unique_ptrdisables copying and depends on move semantics. - Describe the in-memory layout of
std::shared_ptr, detailing the heap control block, strong versus weak reference counters, and the allocation difference betweenstd::make_sharedand passing anewpointer directly. - Show how mutual
std::shared_ptrlinks create memory-leaking cycles, howstd::weak_ptrbreaks those cycles, and howstd::weak_ptr::locksafely promotes an observer when the target object might already be destroyed. Provide a concise C++std::weak_ptr::locksnippet.
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
qsortcomparison and race-freestd::weak_ptr::lockpromotion. - 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
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
qsortis the canonical example:void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));Because
qsortonly knowsbase(start address),nmemb(number of elements), andsize(bytes per element), it treats the array as raw bytes. To reach elementi, it computes(char *)base + i * size, and to swap two elements, it copiessizebytes 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*16Whenever
qsortneeds to know which of two elements comes first, it callscompar(elem_a, elem_b). Inside the callback, we cast theconst void *pointers back toconst 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 arbitraryintvalues. Ifa->ageisINT_MIN(-2147483648) andb->ageis1, 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 Cqsort. Standardqsortcannot pass extra state (like ascending vs. descending) tocomparwithout global/thread-local variables; POSIX.1-2024 standardizedqsort_rto pass an extravoid *argcontext pointer.Preprocessor container generators and C11 _Generic
The second C generic technique is macro metaprogramming: using
#definepreprocessor text substitution before compilation to stamp out separate, fully typed structs andstatic inlinefunctions 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, turningNAME##_pushintoIntVec_push. Because the compiler sees realint *anddouble *types after preprocessing, it type-checks every call and can inlineIntVec_pushright 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, soprint_value(i++)incrementsijust once. Still,_Genericis only compile-time dispatch over already-existing functions (print_int,print_double,print_str), each of which must have its own distinct C name.Object symbols, ABIs, and why C omits function overloading
To understand why C forbids two functions named
max(int, int)andmax(double, double), look at how the compiler and linker (the tool that stitches compiled.oobject 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 (
maxon Linux ELF;_maxwith a single leading underscore on macOS Mach-O). Parameter types are not encoded in the symbol at all. Defining twomaxfunctions produces two identicalmaxsymbols, 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 (
_Z3maxiivs._Z3maxddon 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:
- 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'sextern "C", Go'scgo, assembly routines, and OS system libraries look up functions by their plain C name. Even C++ usesextern "C"to disable name mangling when exposing C-compatible APIs (which immediately disables overloading on those functions). - 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.
- 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
- Direct symbol mapping in C: A C compiler emits the function's plain identifier as its external symbol (
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 collisionsWorked numeric example for performance: Sorting
n = 1,000,00032-bit integers takes roughlyn * log2(n) ≈ 20,000,000comparisons. Withqsort, 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 lengthsize = 4. With a macro-generatedsort_int(or C++std::sort),a < bcompiles 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 tinystatic inlinetyped helper functions or macros so callers still get compile-time type checking.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 earlyreturn,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 oneunique_ptrowns theTobject at any moment. When thatunique_ptris destroyed or reset, it deletes theT. With the default deleter,sizeof(std::unique_ptr<T>)is 8 bytes on 64-bit platforms (identical to a rawT *) with zero atomic or heap overhead. -std::shared_ptr<T>(shared ownership): Multipleshared_ptrinstances co-own the sameTobject. Copying increments an atomic reference count; destroying decrements it, and the last owner to reach count0deletes theT.Why move semantics are mandatory for
std::unique_ptr: Supposeunique_ptrallowed ordinary copying (b = a). Bothaandbwould hold the same raw pointer0x5000. Whenbleft scope its destructor woulddelete 0x5000, and whenaleft scope its destructor woulddelete 0x5000a second time—a double free (heap corruption / undefined behavior). Therefore,unique_ptrexplicitly 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 resizingstd::vector,unique_ptrrelies on move semantics: transferring the raw pointer into the destinationunique_ptrwhile setting the sourceunique_ptrtonullptr, 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)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 theTobject (for fast*pandp->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 activestd::shared_ptrinstances co-owning theT. When the strong count drops to0, theTobject's destructor runs immediately. - Weak reference count: Number of activestd::weak_ptrobservers pointing at this control block. The control block's own memory cannot be freed until both the strong count and the weak count reach0, so aweak_ptrcan always safely inspect the control block to ask whether theThas 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 toTin memory, improving CPU cache locality.std::make_shared<T>(...)trade-offs: Because the control block andTlive in a single malloc block, ifstrongdrops to0(~T()runs) while a long-livedweak_ptrstill holdsweak > 0, the raw memory forTcannot be returned to the heap allocator until the lastweak_ptris also destroyed. Also,make_sharedcannot accept a custom deleter (which requires theshared_ptr(ptr, deleter)constructor).- Thread-safety note: Control-block reference-count updates use atomic instructions, so copying/destroying separate
shared_ptrvariables pointing to the sameTacross threads is safe, but reading/mutating theTobject itself (or mutating the sameshared_ptrinstance from two threads without synchronization) still requires a lock orstd::atomic<std::shared_ptr<T>>.
Breaking reference cycles safely with std::weak_ptr::lock()
Why cyclic
shared_ptrreferences leak: Reference counting has no cycle detector. If aParentholds ashared_ptr<Child>and thatChildholds ashared_ptr<Parent>, each object keeps the other's strong count at>= 1even 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_ptrbreaks cycles: Model ownership as a tree or directed acyclic graph (DAG) where parent-to-child owning edges usestd::shared_ptrand back-pointers, caches, or observer lists usestd::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_ptrprovides no*or->operator. Instead, you callw.lock(), which performs an atomic compare-and-swap check on the control block: - Ifstrong_count > 0, it atomically incrementsstrong_countand returns a new owningstd::shared_ptr<T>that guarantees the object stays alive for the duration of your local scope. - Ifstrong_count == 0, it returns an emptystd::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 lastshared_ptrright betweenexpired()andlock()—a TOCTOU (time-of-check to time-of-use) race condition—makingpnull and crashing onp->. Callinglock()once and testing the returnedshared_ptris 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 (#definecontainer 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_Z3maxiivs._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: storedT *+ control-block pointer) shares ownership via atomic reference updates. - Two counters inside the
shared_ptrcontrol block: The strong count governs object lifetime (strong -> 0runs~T()), whereas the weak count governs control-block memory lifetime (strong == 0andweak -> 0frees the control block). - Breaking cycles safely with
std::weak_ptr::lock(): Replacing back-edges (child -> parent) withweak_ptrprevents strong-count cycles, andw.lock()uses an atomic compare-and-swap operation to return either a valid owningshared_ptrornullptrin one thread-safe step.
Common mistakes
- Subtracting integers inside a C
qsortcomparator (return a - b;): Subtracting1fromINT_MINoverflows signedint(undefined behavior in C and wrong sort sign on two's-complement hardware); use(a > b) - (a < b)instead. - Confusing C11
_Genericwith true function overloading:_Genericonly 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))evaluateMAX(i++, j)twice; preferstatic inlinefunctions 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 count1each, causing a double free; always construct once withstd::make_shared(or usestd::enable_shared_from_thisinside methods) and copy theshared_ptr. - Checking
if (!w.expired())beforew.lock(): In multithreaded code, another thread can destroy the lastshared_ptrbetween the two calls—a TOCTOU (time-of-check to time-of-use) race condition—leavingw.lock()null; always callif (auto p = w.lock())once. - Assuming
std::shared_ptrmakes the pointed-toTthread-safe: Only the control block's reference counts are atomic; concurrent mutations toT's fields still require synchronization.
Follow-up questions
- How does constructing a
std::shared_ptrwithstd::make_sharedcompare against wrapping anewpointer in terms of heap allocations, cache behavior, and memory reclamation? Wrapping anewpointer (std::shared_ptr<T>(new T())) performs two separate heap allocations—one forTand a second for the control block—paying allocator bookkeeping twice and often placing the reference counts andT'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 thatmake_sharedcannot take a custom deleter, and if a long-livedstd::weak_ptroutlives allshared_ptrs,~T()runs immediately when the strong count hits0while the combined heap block's raw memory stays reserved until the weak count also hits0. - Why does a custom deleter affect
sizeof(std::unique_ptr)and its static type, whereasstd::shared_ptrkeeps a fixed size and type regardless of deleter? Instd::unique_ptr<T, D>, the deleter typeDis encoded directly in the template type and stored inline inside theunique_ptrvia empty base optimization (a compiler layout rule allowing stateless types like default deleters or captureless lambdas to occupy 0 extra bytes), keepingunique_ptrat 8 bytes with an inlined cleanup call—whereas a function-pointer deleter growssizeofto 16 bytes and prevents mixing differently-deletedunique_ptrs in onestd::vector. Instd::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 everyshared_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 astruct refcountfield inside your object, initializerefsto1on creation, increment withmemory_order_relaxedinref_retain(safe because the caller already holds a live reference), and decrement withmemory_order_acq_relinref_releaseso all prior writes across threads are visible before invokingdestroywhen the old count was1. Insidedestroy, recover the enclosing struct pointer viaoffsetofandfreeit:
#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
- 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?
- 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?
- How would you build an intrusive reference-counting mechanism in plain C, including the embedded struct layout and atomic retain/release functions?
Similar questions
- Deadlocks, Cache-Line False Sharing, Spinlocks, and Kernel Traps
- Enterprise RAG Architecture Over 10 Million Documents
- Zero-Oversell Ordering Backend for Scarce Menu Items
- Find the Cluster Orchestrator Node
- Splice Two Ordered Linked Lists
- Triaging Competing Urgent Engineering Work
More Netapp interview questions
- Deadlocks, Cache-Line False Sharing, Spinlocks, and Kernel Traps Easy
- Enterprise RAG Architecture Over 10 Million Documents Medium
- Zero-Oversell Ordering Backend for Scarce Menu Items Medium Pro
- Find the Cluster Orchestrator Node Medium Pro
- Splice Two Ordered Linked Lists Medium Pro
- Triaging Competing Urgent Engineering Work Medium Pro
- Compute Standings from Ranked Ballots Medium Pro
- Navigating Technical Disagreements With a Peer Medium Pro