Skip to main content
Be Bitwise
C++What Your C++ Code Actually Does

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

cpp
#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 here
asm
process_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
ret

The 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.

cpp
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):

asm
; 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_Resume

The 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.

Why Is This Possible?

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-64
C Source
1void shared_ptr_version() {
2 auto p = std::make_shared<int>(42);
3 auto q = p; // Increment reference count
4 *q = 100;
5} // q destroyed: decrement ref count
6 // p destroyed: decrement ref count, ref count = 0, delete the int
Assembly
1shared_ptr_version:
2 push rbx
3 mov edi, 24 ; Allocates MORE than sizeof(int)!
4 call operator new(unsigned long)
5 mov rbx, rax
6
7 ; Initialize the control block:
8 mov QWORD PTR [rax], OFFSET vtable_for_shared_ptr_control_block
9 mov DWORD PTR [rax+8], 1 ; Strong ref count = 1
10 mov DWORD PTR [rax+12], 1 ; Weak ref count = 1
11 mov DWORD PTR [rax+16], 42 ; The actual int value
12
13 ; auto q = p: increment reference count
14 lock add DWORD PTR [rbx+8], 1 ; ATOMIC increment of strong ref count
15
16 ; *q = 100
17 mov DWORD PTR [rbx+16], 100
18
19 ; Destroy q: atomic decrement
20 lock sub DWORD PTR [rbx+8], 1 ; ATOMIC decrement
21 je .release ; If count hit 0, release (not here: p still holds a ref)
22
23 ; Destroy p: atomic decrement
24 lock sub DWORD PTR [rbx+8], 1 ; ATOMIC decrement
25 jne .done ; If count > 0, someone else will free
26.release:
27 ; ... call destructor and deallocate ...
28
29.done:
30 pop rbx
31 ret

Hover over code lines or mapping badges to see correspondences

What shared_ptr actually costs:

  1. Extra memory. make_shared allocates a control block alongside the object. Wrapping a 4-byte int saddles you with roughly 20 extra bytes.

  2. Atomic operations. Every copy and destruction uses lock add or lock 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.

  3. 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:

cpp
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.

asm
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:

cpp
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):

asm
; 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:

TypesizeofContents
Raw int*8 bytesJust a pointer
unique_ptr<int>8 bytesJust a pointer (same!)
shared_ptr<int>16 bytesPointer + control block pointer
weak_ptr<int>16 bytesPointer + control block pointer

And the control block for shared_ptr:

FieldSizePurpose
vtable pointer8 bytesFor custom deleters
Strong ref count4 bytesNumber of shared_ptrs
Weak ref count4 bytesNumber of weak_ptrs + 1
(optional) ObjectvariesWith make_shared, stored here

Key Takeaways

  1. unique_ptr is 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 take T* or T& when the callee doesn't need ownership.

  2. shared_ptr charges 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.

  3. RAII boils down to compiler-inserted destructor calls. A call destructor at every scope exit, including the exception paths. The mechanism is plain. The discipline of it is what keeps C++ resource handling safe.

  4. 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.