“实现Drop trait后借入的值寿命不足”

问题描述 投票:1回答:1

刚开始生锈时,我想使用一些数据结构,最后得到一个没有有效负载的节点类型。

use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::Drop;

#[derive(Debug)]
struct Container<'a> {
    next : Option<&'a RefCell<Container<'a>>>,
}

impl<'a> Container<'a> {
    fn new() -> Container<'a> {
        Container { next: None }
    }

    fn set(&mut self, next: &'a RefCell<Container<'a>>) {
        self.next = Some(next);
    }
}

目标是让这些节点not拥有自己的邻居,因此std :: rc :: Rc成为不可能。所以我做了一些测试,一切都很好:

fn main() {
    // items:
    let cont_1 = RefCell::new(Container::new());
    let cont_2 = RefCell::new(Container::new());

    let b_1 = &cont_1;
    let b_2 = &cont_2;

    (*b_2).borrow_mut().set(b_1);
    (*b_1).borrow_mut().set(b_2);

    println!("{:?}", b_1.borrow());
}

由于我一直在玩耍,所以我尝试在Container类型上实现Drop特性

impl<'a> Drop for Container<'a>{
    fn drop(&mut self) {}
}

这将导致两个(另外一个是cont_2)

error[E0597]: `cont_1` does not live long enough
  --> src/main.rs:11:15
   |
11 |     let b_1 = &cont_1;
   |               ^^^^^^^ borrowed value does not live long enough
...
18 | }
   | -
   | |
   | `cont_1` dropped here while still borrowed
   | borrow might be used here, when `cont_1` is dropped and runs the destructor for type `std::cell::RefCell<Container<'_>>`

现在,我相信Drop会导致释放在作用域的末尾,否则通常会在最后一次使用后发生?但是,无论哪种方式,抱怨都是关于没有足够长的价值……我试图在两者之间添加drop(...),但失败了。我想我什至不了解释放顺序的确切变化。我希望cont_1会在最后被释放,因为它首先被初始化/声明,这意味着我不太了解如何仍然可以借用它。

刚开始生锈时,我想使用一些数据结构,最后得到的节点类型没有有效负载。使用std :: cell :: RefCell;使用std :: collections :: HashMap;使用std :: ops :: Drop; #...
rust
1个回答
0
投票
如果在drop()实现中使用self.next.unwrap()...,会发生什么?由于您的一个变量必须先于另一个变量被删除,因此最后一个变量将具有悬空引用,因此

undefined behavior

© www.soinside.com 2019 - 2024. All rights reserved.