Hard
PhantomData<T> in a hand-rolled smart pointer
This MyBox<T> wraps a raw pointer and manually drops what it points to. ptr: *mut T already mentions T, so what does the _marker: PhantomData<T> field actually change about this code?
main.rs
use std::marker::PhantomData;
struct MyBox<T> {
ptr: *mut T,
_marker: PhantomData<T>,
}
impl<T> MyBox<T> {
fn new(value: T) -> Self {
let boxed = Box::new(value);
MyBox { ptr: Box::into_raw(boxed), _marker: PhantomData }
}
}
impl<T> Drop for MyBox<T> {
fn drop(&mut self) {
unsafe {
drop(Box::from_raw(self.ptr));
}
}
}
fn main() {
let b = MyBox::new(5);
unsafe {
println!("{}", *b.ptr);
}
}30 of 53 in Rust