use std::ops::Deref;
struct Test {
last: &'static str,
list: Vec<String>,
}
// This is safe because we own the value and will not modify it.
// When dropping, `last` will be dropped without freeing the memory.
impl Test {
pub fn new(value: String) -> Self {
Self {
last: unsafe { std::mem::transmute(value.deref()) },
list: vec![value],
}
}
pub fn insert(&mut self, value: String) {
self.last = unsafe { std::mem::transmute(value.deref()) };
self.list.push(value);
}
pub fn last(&self) -> &str {
self.last
}
}
有没有可能用泛型做类似的构造,比如Test<T:Deref>
? 我不确定deref()
是否保证了任何"永久"堆地址(在我的实现的有限上下文中),或者它保证了吗?
上面的代码似乎是安全的,因为在String
上调用deref()
会给出一个指向堆的宽指针,并且该地址永远不会改变,除非字符串本身被更改或者所有权被返还给调用者.
请注意,我需要为我的用例存储&str
,而不是使用ManuallyDrop::new(unsafe { ptr::read(&value) })
创建的ManuallyDrop<String>
.