Using PhantomData to indicate ownership


#1

I am trying to figure out what exactly is the effect of adding PhantomData to my program. I understood what’s going on with unused lifetime parameters, and how PhantomData helps Rust infer the right variance of the type.

However, the documentation mentions two more use-cases for PhantomData, that are about ownership. In particular, the paragraph “Indicating ownership” is slightly puzzling. I understand that *mut T does not imply any kind of ownership of a T, while PhantomData<T> does. But what I’d like to know is - why should I care? What exactly is Rust doing differently when I add a PhantomData<T> to my unsafe container managing data of type T?

If you’d like to see example code, here it is. LinkedList contains PhantomData, but I don’t actually know why, or what would go wrong if I would remove it.


#3

The ownership aspect is important for “Sound Generic Drop”, although this may be being tweaked with specialisation.


#4

That LinkedList design must contain PhantomData because it owns T’s and
none of its other subfields otherwise state that. See
http://cglab.ca/~abeinges/blah/turpl/_book/phantom-data.html


#5

Thanks for the pointers!


#6

How do errors manifest themselves in that case? How could you trace your errors to a missing owning T field?


#7

I think errors would manifest in Rust accepting destructors (for the container type in question?) that can result in an invalid borrow being used. One would end up seeing undefined behavior.


#8

Hm, I thought safe rust would be UB free. Although this might be one of those cases where Rust doesn’t protect you.


#9

Safe Rust is UB free. We are talking about an unsafely implemented container here. (See the code I linked in my first post.)


#10

Yeah this is only a problem if you have raw pointers and you use them, which is blatantly unsafe.


#11

Oh, I totally, missed the unsafe blocks.