Re:Classes Considered Harmful [pdf]
by steveklabnik on Tuesday January 03, 2017 @08:49PM
(#13315032)
The big difference is that when you have a trait object in Rust, it's a double pointer: a pointer to the vtable, and a pointer to the data. In C++, in my understanding, you'd have a single pointer to both the vtable and data laid out next to each other.
Thanks for that.
What you describe for C++ is typically the case (and I've written completely unsafe, non-portable code that exploits this fact before), but I'm unsure whether that's required by the standard.
Re:Classes Considered Harmful [pdf]
by lacampbell on Tuesday January 03, 2017 @09:48PM
(#13315276)
So rust traits are effectively/functionally abstract classes with restricted functionality and a different implementation?
Re:Classes Considered Harmful [pdf]
by steveklabnik on Tuesday January 03, 2017 @10:30PM
(#13315442)
Sort of. The closest thing in C++ would be concepts. That is, even using traits in this way is the minority case; they're more usually used for monomorphized, statically dispatched code.
But, given the case where you want dynamic dispatch, then in a sense, they are, yes.
Re:Classes Considered Harmful [pdf]
by lacampbell on Tuesday January 03, 2017 @10:43PM
(#13315495)
Right. I suppose in Rust you generally use variants and pattern matching when dynamic dispatching is required.
Re:Classes Considered Harmful [pdf]
by steveklabnik on Tuesday January 03, 2017 @10:55PM
(#13315550)
You could, but that requires that you know all of the variants ahead of time. The advantage of trait objects is that you don't have to.
It really just depends on what exactly you're trying to do.
In practice, one defines an interface in C++ by having a (hopefully) stateless class with pure virtual method declarations, and then classes derived from this class must implement these methods (in order to instantiate them anyway). In Rust one defines a data structure (either a struct or enum) and then, separately, writes the "impl" for it for a trait.