What is the `Phantom Date` actually doing in the implementation of` Vec`?

How does it work PhantomDatain Rust? Nomicon says the following:

In order to tell dropck that we have eigenvalues ​​of type T, and therefore can discard some Ts when falling, we must add an additional PhantomData that says just that.

It seems to me that when adding a field PhantomDatato the structure, say, in the case Vec.

pub struct Vec<T> {
    data: *mut T,
    length: usize,
    capacity: usize,
    phantom: PhantomData<T>,
}

so that the reset controller prohibits the following code sequence:

fn main() -> () {
    let mut vector = Vec::new();

    let x = Box::new(1 as i32);
    let y = Box::new(2 as i32);
    let z = Box::new(3 as i32);

    vector.push(x);
    vector.push(y);
    vector.push(z);
}

Since the release x, yand zwill happen to the release Vec, I expect some complaints from the compiler. However, if you run the above code, there are no warnings or errors.

+4
1

PhantomData<T> Vec<T> ( Unique<T> RawVec<T>) , T, T .


: :

  • Vec<T>, impl Drop (.. ).

  • RFC 1238 Vec<T> , T, , T .

  • Vec<T> ( Vec<T>) (. RFC 1238 RFC 1327). , . ; , , (, , ), .

  • : , , , . T , T . , , , .

  • , : , S, , S impl Drop for S ( , S ). S , dropck. ( , , S #[may_dangle].)

  • Vec<T>, ( RawVec<T>/Unique<T>) T, *const T. *const T; S S T , , S T ( , dropck).

  • , Vec<T> a *const T, T, , #[may_dangle] T , ( , T ).

  • : Vec<T> *const T. PhantomData<T>, ", (- #[may_dangle] T), Vec T, drop, , - T T ."

: Vec<T>, T , ( , , , , ). T ( , - ), , , , , ( , T - ).

+3

Source: https://habr.com/ru/post/1666143/


All Articles