← Back to context

Comment by tialaramex

13 hours ago

This has a section on Object Safety, I checked and the article was written this week, but "Object Safety" is a confusing name for this idea, and so for a little while now Rust calls this idea "dyn compatibility" because the most important thing you're getting if a trait is "dyn compatible" is that you can use "dyn Trait" - https://doc.rust-lang.org/1.98.1/reference/items/traits.html...

That link more comprehensively explains the rules too.

[Edit: Realized the end of the article explains this, the author began writing it months ago, likely before they read about the improved "dyn compatibility" naming]

The aside about C++ seems a little confused too?

> C++ doesn’t have this problem at all, since virtual dispatch always goes through pointers and return types are always pointers too.

Uh. C++ can return objects by value. Maybe it isn't idiomatic. And I don't know if there's a convenient spelling like `Self`. But it runs into the same problem, of course -- you would need to know the concrete value type returned to have storage for it.

And Rust has the ~same solution as imagined for C++ here, I think? Have a `DynClone` trait that returns `Box<dyn Trait>` instead of `Self`.

  • Polymorphism in C++ can only be correct on pointers and references (which are pointers internally).

    Stack-allocated objects and polymorphism only combine if the object is initialized as its true type and a pointer or reference to it is handed out. Obviously, this can create object lifetime issues if the pointer or reference escapes the lifetime of the stack frame containing the object.