Ok, I would like to rollback to some old rust edition to make the following code compiled, wrongly, which must use PhantomData to fail the compilation.
use std::marker;
struct vvec<T> {
data: *const T, // *const for variance!
len: usize,
// _owns_t: marker::PhantomData<T>,
}
impl<T> vvec<T> {
fn new() -> Self {
vvec {
data: 0 as *const T,
len: 1,
// _owns_t: marker::PhantomData::<T>,
}
}
fn push(&mut self, _x: T) {}
}
impl<T> Drop for vvec<T> {
fn drop(&mut self) {}
}
fn main() {
let mut v: vvec<&str> = vvec::new();
{
{
let s: String = "Short-lived".into();
v.push(&s);
}
}
}
I have tried 1.48, 1.40. Both refuse to compile.
According to the document:
Another important example is Vec, which is (approximately) defined as follows:
struct Vec<T> { data: *const T, // *const for variance! len: usize, cap: usize, }Unlike the previous example, it appears that everything is exactly as we want. Every generic argument to Vec shows up in at least one field. Good to go!
Nope.
The drop checker will generously determine that Vec does not own any values of type T. This will in turn make it conclude that it doesn't need to worry about Vec dropping any T's in its destructor for determining drop check soundness. This will in turn allow people to create > unsoundness using Vec's destructor.
In order to tell the drop checker that we do own values of type T, and therefore may drop some T's when we drop, we must add an extra PhantomData saying exactly that:
use std::marker; struct Vec<T> { data: *const T, // *const for variance! len: usize, cap: usize, _owns_T: marker::PhantomData<T>, }
There should be a version that compiler will pass the compilation, but I can't find such a version. 1.40 is a very old version, which I am sure the new behavior of
But ever since RFC 1238, this is no longer true nor necessary. did not apply yet.
Or, There is some misunderstanding, maybe
fn main() {
let mut v: vvec<&str> = vvec::new();
{
{
let s: String = "Short-lived".into();
v.push(&s);
}
}
}
is not the correct example to show how unsoundness occurs without PhantomData