Sub topic 5
Fat pointers and vtables
This chapter assumes you know what dyn Trait means and why trait objects must sit behind a pointer such as &dyn Trait or Box<dyn Trait>. Here we look at what that pointer contains and what the compiler builds so a method call can be resolved at runtime.
Why a plain pointer is not enough
A &Circle points at a Circle, and the compiler knows its type. It knows the size and which area to call. A &dyn Shape has lost the concrete type, so the pointer alone cannot say which area to run or how big the value is.
Rust solves this by making the pointer wider. A pointer to an unsized type is a fat pointer, which holds two machine words:
- A data pointer to the value.
- Extra metadata that completes the type information.
For dyn Trait, the metadata is a pointer to a vtable (virtual method table). For a slice such as &[T], the metadata is the length instead.
Measuring the difference
You can see the extra word with size_of:
use std::fmt::Debug;
use std::mem::size_of;
fn main() {
// On a 64-bit target:
println!("{}", size_of::<&u8>()); // 8: a thin pointer
println!("{}", size_of::<&[u8]>()); // 16: data pointer + length
println!("{}", size_of::<&dyn Debug>()); // 16: data pointer + vtable pointer
println!("{}", size_of::<Box<dyn Debug>>()); // 16
}Box<dyn Debug> has the same layout as &dyn Debug. Rc<dyn Trait> and Arc<dyn Trait> are also two words wide, because their pointer to the shared allocation is fat.
What a vtable holds
The compiler generates one vtable for each pair of concrete type and trait. For Circle as dyn Shape, the vtable holds these entries:
- A function that drops the value (
drop_in_place). - The size of the concrete type.
- The alignment of the concrete type.
- A function pointer for each method that is in the trait and callable through
dyn.
The layout of a vtable is an implementation detail. The language does not promise an order or a format, so you cannot rely on it in your code.
What the vtable does at runtime
A call such as s.area() on a &dyn Shape compiles to roughly three steps:
- Read the vtable pointer from the fat pointer.
- Load the
areafunction pointer from a fixed slot in that vtable. - Call it, passing the data pointer as
self.
The slot position is known at compile time. Only the vtable that is found there changes at runtime. This is one extra memory load and an indirect call. The compiler usually cannot inline an indirect call, and that is the main cost of dynamic dispatch.
The size and alignment entries are also used. When you drop a Box<dyn Shape>, Rust calls the vtable's drop function and then frees the memory using the stored size and alignment. Likewise, size_of_val on a trait object reads the vtable:
use std::fmt::Debug;
use std::mem::size_of_val;
fn main() {
let small: Box<dyn Debug> = Box::new(1u8);
let big: Box<dyn Debug> = Box::new([0u64; 4]);
println!("{}", size_of_val(&*small)); // 1
println!("{}", size_of_val(&*big)); // 32
}Both boxes have the same type and the same 16-byte size. They report different sizes for the values behind them.
Common mistakes
- Assuming
Box<dyn Trait>is as small asBox<T>. It is twice as large. - Casting a
*const dyn Traitto a thin pointer such as*const u8. This keeps only the data address and drops the vtable. - Expecting the compiler to inline through a trait object. It can only do so if it can prove the concrete type.
Exercise
On a 64-bit target, what is size_of::<Rc<dyn Debug>>(), and what are the two words it holds?
Show answer
It is 16 bytes. One word is the pointer to the shared allocation (the reference counts and the value). The other is the vtable pointer for the concrete type behind the dyn Debug.