< 返回版块

goerzh 发表于 2020-01-02 11:54

use std::ptr;

struct MyCell<'a> {
    value: &'a i32,
}

impl<'a> MyCell<'a> {
    fn new(x: &'a i32) -> MyCell<'a> {
        MyCell {value: x}
    }
    fn get(&self) -> i32 {
        *self.value
    }
    fn set(&self, value: &'a i32) {
        unsafe {
            ptr::write(&self.value as *const _ as *mut _, value);
        }
    }
}

fn step<'a>(r_c1: &mut MyCell<'a>) {
    let val: i32 = 13;
    r_c1.set(&val);
    println!("step1 value: {}", r_c1.value);
}

fn main() {
    let x = 3;
    let mut cell = MyCell::new(&x);
    step(&mut cell);
    println!("end value: {}", cell.value);
}

MyCell::set 方法的value用 ’a 标记了,不是应该传入存活时间比MyCell本身长的值吗?为什么生命周期检测没有生效呢?


Ext Link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=abe2aa201ad53cd72e84cf38f494b115

评论区

写评论
Nugine 2020-01-05 11:50

https://zhuanlan.zhihu.com/p/100993632

这篇文章解释了这里的生命周期问题

zyctree 2020-01-04 20:32

反过来说, 你也可以说 MyCell 的存活时间要比 val 长

因为调用的时候 r_c1 的类型变了, 现有 &'b MyCell<'a>&'c i32

'a : 'c => MyCell<'a> : MyCell<'c> => &'b MyCell<'a> : &'b MyCell<'c>

为了让它不变, 将 'a 变成 invariant,

struct MyCell<'a> {
    value: &'a i32,
    _data: std::marker::PhantomData<std::cell::Cell<&'a()>>
}

就会出现你想要的生命周期检测

作者 goerzh 2020-01-03 10:15

去掉unsafe是可以的。我的问题是,在set方法的value参数上的’a标记怎么没有起作用呢

对以下内容的回复:

你用unsafe绕开检查了。 把unsafe去掉,参数改成&mut self 试试。
yuanyunchang 2020-01-02 19:36

你用unsafe绕开检查了。 把unsafe去掉,参数改成&mut self 试试。

1 共 4 条评论, 1 页