Sub topic 5
Fat pointers and vtables
This chapter assumes you can write and implement traits, use Box and references, and have seen dyn Trait and Vec<Box<dyn Trait>>. Here you will look at what a trait object value is in memory and how a method call finds the right code at runtime.
Thin pointers and fat pointers
A reference such as &u8 or &Circle is a thin pointer. It holds one machine word, the address of a value, and the compiler already knows the value's type and size.
A reference to a type of unknown size needs more information. dyn Shape is unsized, so a pointer to one is a fat pointer with two words:
- A data pointer to the concrete value.
- Extra metadata the compiler needs to work with that value.
For a slice, the metadata is the length. For a trait object, it is a pointer to a vtable, a table of facts and function pointers for the concrete type behind the pointer.
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::<&dyn Debug>()); // 16: data pointer + vtable pointer
println!("{}", size_of::<Box<dyn Debug>>()); // 16
}The same split applies to every pointer type that can hold an unsized value.
| Type | Size on 64-bit | Contents |
|---|---|---|
| `&T`, `Box<T>` (sized `T`) | 8 | data pointer |
| `&[T]`, `&str` | 16 | data pointer, length |
| `&dyn Trait`, `Box<dyn Trait>` | 16 | data pointer, vtable pointer |
| `Rc<dyn Trait>`, `Arc<dyn Trait>` | 16 | pointer to the allocation, vtable pointer |
For Rc<dyn Trait> and Arc<dyn Trait>, the data pointer refers to the heap allocation that holds the reference counts and the value. The vtable still describes the value's concrete type.
What a vtable contains
The compiler generates one vtable for each pair of a concrete type and a trait it is converted to a trait object for. For Circle used as dyn Shape, there is one Circle/Shape vtable. It is built at compile time and stored in read-only static memory. Every &dyn Shape that points at a Circle shares it, and no vtable is allocated per object.
In current compilers, a vtable holds these entries:
- A pointer to the type's drop glue, the code that drops the value in place.
- The size of the concrete type.
- The alignment of the concrete type.
- One function pointer for each dyn-compatible method of the trait, in declaration order.
The exact layout is an implementation detail of rustc. Do not write code that depends on it. The entries themselves are not an accident, though, because each one supports a language feature:
- The drop entry lets
Box<dyn Shape>free its contents correctly without knowing the type. Dropping the box calls the entry to run the concrete type's destructor, then deallocates using the stored size and alignment. - Size and alignment let
Box<dyn Shape>deallocate with the right layout. They also letstd::mem::size_of_valwork on an unsized value. - Method pointers are what dynamic dispatch calls.
A default method such as name in the Shape trait from earlier chapters still gets a vtable slot. For a type that does not override it, the slot points to the default body compiled for that type. For a type that overrides it, the slot points to the override.
use std::fmt::Debug;
use std::mem::size_of_val;
fn main() {
let a: Box<dyn Debug> = Box::new(5u8);
let b: Box<dyn Debug> = Box::new([0u64; 4]);
// &*a is a &dyn Debug. size_of_val reads the size from the vtable.
println!("{} {}", size_of_val(&*a), size_of_val(&*b)); // 1 32
// The boxes themselves are the same size: two words each.
println!("{} {}", size_of_val(&a), size_of_val(&b)); // 16 16
}The two boxes have the same type, so they have the same size. Only the vtable pointer inside each one tells the program that one value is 1 byte and the other is 32.
Building a vtable by hand
The following program does by hand what the compiler does for you. It uses a struct of function pointers as the vtable and a pair of data pointer and vtable reference as the fat pointer. It is for illustration only, since real code should use dyn.
struct Square(f64);
struct Circle(f64);
struct VTable {
area: fn(*const ()) -> f64,
name: &'static str,
}
fn square_area(p: *const ()) -> f64 {
// Safety: only called with a pointer to a Square.
let s = unsafe { &*(p as *const Square) };
s.0 * s.0
}
fn circle_area(p: *const ()) -> f64 {
// Safety: only called with a pointer to a Circle.
let c = unsafe { &*(p as *const Circle) };
3.0 * c.0 * c.0
}
static SQUARE_VT: VTable = VTable { area: square_area, name: "square" };
static CIRCLE_VT: VTable = VTable { area: circle_area, name: "circle" };
struct FatRef {
data: *const (),
vtable: &'static VTable,
}
fn main() {
let sq = Square(3.0);
let ci = Circle(1.0);
let items = [
FatRef { data: &sq as *const Square as *const (), vtable: &SQUARE_VT },
FatRef { data: &ci as *const Circle as *const (), vtable: &CIRCLE_VT },
];
for it in &items {
println!("{} {}", it.vtable.name, (it.vtable.area)(it.data));
}
}This prints square 9 and then circle 3. The loop body does not know which type it is handling. It follows vtable to a function pointer and passes data to it. The real dyn machinery does the same, except the compiler generates the table and checks that the types match, so there is no unsafe in your code.
Where the fat pointer is created
The vtable pointer is attached when a pointer to a sized type is converted to a pointer to dyn Trait. This conversion is called an unsizing coercion. At that point the compiler still knows the concrete type, so it can pick the right vtable.
use std::rc::Rc;
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
let sq = Square(2.0);
let r: &dyn Shape = &sq; // &Square -> &dyn Shape
let b: Box<dyn Shape> = Box::new(Square(3.0)); // Box<Square> -> Box<dyn Shape>
let rc: Rc<dyn Shape> = Rc::new(Square(4.0)); // Rc<Square> -> Rc<dyn Shape>
println!("{} {} {}", r.area(), b.area(), rc.area());
}This prints 4 9 16. After the coercion, the concrete type is gone from the static type. The vtable pointer is the only remaining record of it.
Consequences you will notice
- Size. Every trait object pointer is twice the size of a thin pointer. This matters when you store millions of them, and rarely otherwise.
- No type recovery for free. The vtable has no field for "what type am I". Getting the concrete type back needs
dyn Any, covered in a later chapter. - Calls cost an indirect jump. The call goes through a function pointer, and the compiler usually cannot inline it. The cost of the lookup is small. The missed inlining is often the bigger cost in hot loops.
- Methods have a fixed receiver form. A vtable entry is a function with a known signature that takes the data pointer. A method that needs
Selfby value, or that is generic, has no fixed entry. This is the root of the dyn compatibility rules in a later chapter.
Exercise
On a 64-bit target, what are the values of size_of::<Box<dyn Debug>>(), size_of::<Box<u64>>(), and size_of::<&[u8]>(), and what does each pointer hold? Then explain how Box<dyn Debug> knows how much memory to free when it is dropped.
Show answer
They are 16, 8, and 16. Box<dyn Debug> holds a data pointer and a vtable pointer. Box<u64> holds only a data pointer, since u64 is sized. &[u8] holds a data pointer and a length. When the box is dropped, it reads the drop glue, size, and alignment from the vtable. It runs the destructor of the concrete type and then deallocates using that size and alignment.