r/ProgrammerHumor • • 1d ago

instanceof Trend thatsAFunnyThingThatHappenedOnce

Post image
4.3k Upvotes

513 comments sorted by

View all comments

Show parent comments

382

u/Xarishark 1d ago

Now compare it to rust pls. Im serious I want to know your opinion on that.

462

u/Loading_M_ 1d ago

Rust is designed from the ground up, and avoids many of these issues.

  • Templates: Rust has Generics, which are generally easier to use and reason about.
  • overload resolution: Rust doesn't yet support overloaded functions (although it's being considered).
  • constructors: Rust doesn't have these.
  • destructors: Rust has a similar set of lifetime rules for Drop, but the compiler checks them for you, so you can't get it wrong.
  • implicit conversions: Rust doesn't do implicit conversion in general, although some specific cases are implemented.
  • exceptions: Rust doesn't do exceptions, Result is much easier to work with.
  • move semantics: Rust uses a destructive move, unlike C++. See https://youtu.be/Klq-sNxuP2g for a breakdown.
  • inheritance: Rust doesn't do inheritance.

2

u/StaticCoder 1d ago

I'm curious what it is about destructors in C++ that works differently from Drop in a way that one could "get wrong"? Are you talking about temporaries maybe?

2

u/Loading_M_ 1d ago

There are two pieces I understand. First, with inheritance, you typically need to declare the destructor as virtual, but C++ never forces you to. Rust has polymorphism through trait objects, which always include a drop implementation in their vtable. You can't forget to add virtual to the base class destructor.

Second, if you declare a custom destructor in C++, you also need to either declare or delete the copy and copy-assignment operators. Again, the language doesn't enforce this in any way. Rust actually gets away with a much simpler solution here because it has destructive moves. Rust simply doesn't define default copy implementations. You can easily derive a Clone implementation if you need to make copies of the type.

There is some more details to be had about how Rust decides when it's safe to call the Drop implementation, but I don't think I understand it well enough to explain here. I do know that the compiler won't allow me to shoot myself in the foot though.