RAII & Smart Pointers in Assembly
RAII (Resource Acquisition Is Initialisation) is the load-bearing idiom of C++. Resources get cleaned up when their owning objects leave scope, no exceptions. Smart pointers like unique_ptr and shared_ptr are RAII wearing a memory-management hat. In this lesson we'll prove at the assembly level that unique_ptr really is free, see what shared_ptr actually charges, and walk through the cleanup code the compiler emits for exception paths.
RAII: Automatic Destructor Calls
#include <memory>#include <cstdio>
class FileHandle { FILE *fp;public: FileHandle(const char *path) : fp(fopen(path, "r")) {} ~FileHandle() { if (fp) fclose(fp); } FILE *get() { return fp; }};
void process_file() { FileHandle f("data.txt"); // ... use f.get() ...} // f.~FileHandle() called automatically hereprocess_file: push rbx sub rsp, 16
; Construct FileHandle lea rdi, [rel .LC_path] ; "data.txt" lea rsi, [rel .LC_mode] ; "r" call fopen mov QWORD PTR [rsp], rax ; Store fp in FileHandle on stack
; ... use the file ...
; Destruct FileHandle (compiler-inserted) mov rdi, QWORD PTR [rsp] ; Load fp test rdi, rdi ; if (fp) je .skip_close call fclose ; fclose(fp).skip_close: add rsp, 16 pop rbx retThe compiler slips a destructor call in at every exit point. Multiple returns? Each one gets its own cleanup. Exception thrown mid-function? The unwinder runs the destructors as the stack peels back.
unique_ptr: The Zero-Cost Abstraction
One of C++'s boldest claims. Let's go check.
void use(int *p); // defined in another file, so the compiler can't see inside
void raw_pointer_version() { int *p = new int(42); use(p); delete p;}
void unique_ptr_version() { auto p = std::make_unique<int>(42); use(p.get()); // automatically deleted}The call to use() is there to keep the allocation alive. Without it, GCC and Clang at -O2 both spot that the new/delete pair does nothing observable and compile each function down to a bare ret.
Compiled for x86-64 Linux at -O2 (Clang against libstdc++, symbols demangled):
; raw_pointer_version:raw_pointer_version: push rbx mov edi, 4 ; sizeof(int) call operator new(unsigned long) mov rbx, rax mov DWORD PTR [rax], 42 ; *p = 42 mov rdi, rax call use(int*) mov esi, 4 ; sized delete: sizeof(int) mov rdi, rbx pop rbx jmp operator delete(void*, unsigned long)
; unique_ptr_version:unique_ptr_version: push r14 ; extra: used by the landing pad push rbx push rax ; extra: keeps the stack 16-byte aligned mov edi, 4 call operator new(unsigned long) mov rbx, rax mov DWORD PTR [rax], 42 mov rdi, rax call use(int*) mov esi, 4 mov rdi, rbx add rsp, 8 pop rbx pop r14 jmp operator delete(void*, unsigned long)
; Landing pad: only reached if use() throws mov r14, rax ; save the exception mov esi, 4 mov rdi, rbx call operator delete(void*, unsigned long) mov rdi, r14 call _Unwind_ResumeThe work is identical: the same allocation, the same store, the same call, the same sized delete. What the unique_ptr version adds is exception safety. It gets a landing pad that frees the int if use() throws, where the raw version would just leak it, and the function saves a couple of extra registers to support that pad. GCC's output has the same shape.
unique_ptr is a featherweight wrapper. One pointer of state, 8 bytes, same as a raw pointer, and a destructor that just calls delete. With inlining and optimisation turned on, the compiler peers straight through and emits the code it would have for manual memory management. The abstraction costs nothing precisely because it hands the compiler enough information to fold it away.
shared_ptr: The Reference Counting Overhead
shared_ptr is the opposite story. The reference count has to live somewhere, and that somewhere has to be reachable from every copy.
Hover a source line to light up the instructions it became. The listing is simplified: recent libstdc++ also checks whether the program has started any threads before taking the atomic path. The three lock-prefixed instructions are the copy and the two destructions.
shared_ptr copy and destruction (simplified)
x86-64Hover over code lines or mapping badges to see correspondences
What shared_ptr actually costs:
-
Extra memory.
make_sharedallocates a control block alongside the object. Wrapping a 4-byteintsaddles you with roughly 20 extra bytes. -
Atomic operations. Every copy and destruction uses
lock addorlock sub, the atomic read-modify-write instructions. These are 10-100x more expensive than ordinary increments because they have to make the change visible across every core. -
Cache-line ping-pong. Once multiple threads start sharing a
shared_ptr, those atomics bounce the cache line containing the refcount between cores, and your program quietly grinds.
Exception Safety and Cleanup Tables
Once exceptions enter the picture, the compiler emits cleanup tables tucked into .eh_frame and .gcc_except_table:
void might_throw() { std::unique_ptr<int> a = std::make_unique<int>(1); std::unique_ptr<int> b = std::make_unique<int>(2); // What if this throws? // If b's allocation throws, a must still be destroyed}For each exit, the compiler builds a landing pad: cleanup code the unwinder runs as it walks back up the stack.
might_throw: push rbx sub rsp, 16
; Allocate a mov edi, 4 call operator new(unsigned long) ; Could throw std::bad_alloc mov QWORD PTR [rsp], rax ; Store a mov DWORD PTR [rax], 1
; Allocate b mov edi, 4 call operator new(unsigned long) ; Could throw! mov QWORD PTR [rsp+8], rax mov DWORD PTR [rax], 2
; Normal path: destroy b, then a mov rdi, QWORD PTR [rsp+8] call operator delete(void*, unsigned long) mov rdi, QWORD PTR [rsp] call operator delete(void*, unsigned long) add rsp, 16 pop rbx ret
; Landing pad: if the second 'new' throws, destroy 'a'.L_cleanup_a: mov rdi, QWORD PTR [rsp] ; Load a's pointer call operator delete(void*, unsigned long) ; Delete a ; Re-throw the exception (handled by unwinder)The .eh_frame section holds DWARF unwinding tables, which map every instruction range to its landing pad. That's the trick behind "C++ exceptions are zero cost when nothing throws". The tables sit dormant in the binary, only consulted when an exception actually fires.
Scope Guard Pattern
RAII isn't just for memory. A scope guard tucks any cleanup action behind a destructor:
class ScopeGuard { std::function<void()> cleanup; bool active = true;public: explicit ScopeGuard(std::function<void()> fn) : cleanup(std::move(fn)) {} ~ScopeGuard() { if (active && cleanup) cleanup(); } // empty std::function would throw void dismiss() { active = false; }};
void transaction() { begin_transaction(); ScopeGuard guard([]{ rollback_transaction(); }); // ... do work ... commit_transaction(); guard.dismiss(); // Prevent rollback}In the assembly, it's just a destructor call at scope exit. If the guard is still active, the stored callable gets dispatched through an indirect call to the invoker pointer std::function keeps inside itself (simplified):
; At scope exit: cmp BYTE PTR [rbp-16], 0 ; guard.active? je .skip_cleanup ; dismissed: do nothing lea rdi, [rbp-48] ; the std::function's stored callable call QWORD PTR [rbp-24] ; Call through its invoker pointer.skip_cleanup:Size Comparison
Side-by-side sizes:
| Type | sizeof | Contents |
|---|---|---|
Raw int* | 8 bytes | Just a pointer |
unique_ptr<int> | 8 bytes | Just a pointer (same!) |
shared_ptr<int> | 16 bytes | Pointer + control block pointer |
weak_ptr<int> | 16 bytes | Pointer + control block pointer |
And the control block for shared_ptr:
| Field | Size | Purpose |
|---|---|---|
| vtable pointer | 8 bytes | For custom deleters |
| Strong ref count | 4 bytes | Number of shared_ptrs |
| Weak ref count | 4 bytes | Number of weak_ptrs + 1 |
| (optional) Object | varies | With make_shared, stored here |
Key Takeaways
-
unique_ptris zero-cost for local ownership. Crank up optimisation and it emits the same assembly as a raw pointer. Make it your default. The exception is passing it by value: because it has a non-trivial destructor, the Itanium ABI passes it through memory (the caller builds a temporary and hands over its address) rather than in a register, and the caller still runs the moved-from destructor afterwards. That's a few extra instructions per call, so takeT*orT&when the callee doesn't need ownership. -
shared_ptrcharges real money. Atomic refcount updates, an extra heap block, destruction logic the inliner can't see through. Reach for it only when ownership is actually shared. -
RAII boils down to compiler-inserted destructor calls. A
call destructorat every scope exit, including the exception paths. The mechanism is plain. The discipline of it is what keeps C++ resource handling safe. -
Exceptions cost nothing when nothing throws. The DWARF unwind tables sit in the binary, untouched on the happy path. You pay in binary size, and you only pay in cycles when an exception actually fires.