FAQ - Help and questions

How do C++ virtual functions map to Rust trait objects, and what do they cost?

#porting#cpp#traitspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A class with virtual functions becomes a trait, and a pointer to the base class becomes a trait object (Box<dyn Trait> or &dyn Trait). The method is looked up in a table at run time, as in C++. If the set of types is closed, an enum is simpler, and if known at compile time, a generic function avoids the lookup.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Rust offers three tools for "one interface, several types", and a port should choose per case instead of translating every virtual class the same way.

ToolChosen whenDispatch
Generic function with a bound (fn f<T: Shape>)The caller knows the concrete type at compile timeStatic: a copy of the function per type, no lookup
Trait object (&dyn Shape, Box<dyn Shape>)Different types in one collection, or the type is chosen at run timeDynamic: a table lookup per call, like a C++ virtual call
enum with one variant per typeThe set of types is closed and known (you own all of them)A match; no pointers and no lookup

A trait object is a "fat pointer": it holds the pointer to the data and a pointer to the table of methods. The program shows the size of each pointer, then the same total area computed through all three tools. It was compiled and run with rustc 1.93.0 on a 64-bit target.

src/main.rsrust
use std::mem::size_of;

trait Shape {
    fn area(&self) -> f64;
}
struct Circle(f64);
struct Rect(f64, f64);
impl Shape for Circle {
    fn area(&self) -> f64 { 3.14159 * self.0 * self.0 }
}
impl Shape for Rect {
    fn area(&self) -> f64 { self.0 * self.1 }
}

// static dispatch: one copy of the function per type, the call is known at compile time
fn total_static<T: Shape>(items: &[T]) -> f64 {
    items.iter().map(|s| s.area()).sum()
}

// dynamic dispatch: one function, the method is looked up in a table at run time
fn total_dyn(items: &[Box<dyn Shape>]) -> f64 {
    items.iter().map(|s| s.area()).sum()
}

// closed set known now: an enum, no pointers at all
enum Fixed {
    Circle(f64),
    Rect(f64, f64),
}
fn area(s: &Fixed) -> f64 {
    match s {
        Fixed::Circle(r) => 3.14159 * r * r,
        Fixed::Rect(w, h) => w * h,
    }
}

fn main() {
    println!("&Circle {} bytes, &dyn Shape {} bytes, Box<dyn Shape> {} bytes", size_of::<&Circle>(), size_of::<&dyn Shape>(), size_of::<Box<dyn Shape>>());
    println!("{}", total_static(&[Rect(2.0, 3.0), Rect(1.0, 1.0)]));
    let mixed: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Rect(2.0, 3.0))];
    println!("{:.3}", total_dyn(&mixed));
    println!("{:.3}", [Fixed::Circle(1.0), Fixed::Rect(2.0, 3.0)].iter().map(area).sum::<f64>());
}
text
&Circle 8 bytes, &dyn Shape 16 bytes, Box<dyn Shape> 16 bytes
7
9.142
9.142

The pointer to a concrete type is 8 bytes; the trait object is 16, the second 8 being the pointer to the method table. The static version cannot mix Circle and Rect in one slice, because the slice has one element type; that is exactly what Box<dyn Shape> and the enum are for.

No speed claim is made here: a virtual call is usually cheap, and whether it matters depends on the loop. Measure before choosing the more awkward design for speed.

How to do it#

  1. For each abstract base class, list the methods that are virtual. Those become the trait's methods.
  2. For each derived class, write a struct and impl Trait for Struct. Shared data in the base class becomes a field of each struct, a helper struct they all hold, or default methods on the trait (see the thread on classes and inheritance).
  3. Choose the tool per use. A collection of mixed types: Vec<Box<dyn Trait>>. A function used with one type at a time: generic. A closed set that you control and that match can cover: enum.
  4. Replace dynamic_cast by adding a method to the trait, or by matching on an enum. Downcasting exists (Any) but is rarely the right port.

Common mistakes#

  • Returning dyn Trait by value. It has no known size; return Box<dyn Trait>, or impl Trait when the function returns one concrete type.
  • Writing a trait with a generic method and expecting a trait object. A trait is object-safe only if the compiler can build the table: generic methods and methods returning Self are not allowed in it.
  • Using trait objects to imitate an open class hierarchy when an enum would let match check that every case is handled.

Is there a virtual destructor to remember?#

No. Box<dyn Trait> drops the concrete value correctly because the method table includes how to drop it.

Can a trait object be shared?#

Yes: Rc<dyn Trait> and Arc<dyn Trait> work like Box, and &dyn Trait borrows.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet