Dyn pointer equality

The compiler (stable 1.40) seems to generate different vtables for dyn pointers when the same coercion is done in different modules of an rlib. Perhaps rustc and/or linker was not able to recognize that the vtables are the same and dedup them?

This results in ptr::eq(), Rc::ptr_eq() etc returning false, for the same pointer. Is this expected behavior? Feels like a bug to me.

This is expected behavior, but I think this should be better documented

Very surprising behavior! Is there a way to do pointer comparisons of Box<dyn Trait> correctly without resorting to transmute?

1 Like

I don't know a way to dedup the vtables on the fly, but if you only care about comparing the data pointer, you can cast to *const u8 first.

2 Likes

That cast is definitely less fragile than a transmute, and just comparing the data pointer works for me. Thanks.

In a similar vein, can function pointers have different addresses, depending on the coercion site? Especially functions with generic parameters.

Yes, I believe LLVM is told that the address of a function doesn't matter, so it can duplicate and specialize in any way it wants.

2 Likes