rust/tests/compile-fail/rc_as_ptr.rs

21 lines
743 B
Rust
Raw Normal View History

// This should fail even without validation
// compile-flags: -Zmiri-disable-validation
2019-05-29 12:35:47 -05:00
use std::rc::{Rc, Weak};
use std::ptr;
/// Taken from the `Weak::as_ptr` doctest.
2019-05-29 12:35:47 -05:00
fn main() {
let strong = Rc::new(Box::new(42));
let weak = Rc::downgrade(&strong);
// Both point to the same object
assert!(ptr::eq(&*strong, Weak::as_ptr(&weak)));
2019-05-29 12:35:47 -05:00
// The strong here keeps it alive, so we can still access the object.
assert_eq!(42, **unsafe { &*Weak::as_ptr(&weak) });
2019-05-29 12:35:47 -05:00
drop(strong);
// But not any more. We can do Weak::as_raw(&weak), but accessing the pointer would lead to
// undefined behaviour.
assert_eq!(42, **unsafe { &*Weak::as_ptr(&weak) }); //~ ERROR dereferenced after this allocation got freed
2019-05-29 12:35:47 -05:00
}