有什么方法可以允许移动具有借入元素但不能删除它的容器? [英] Is there any way to allow moving a container that has a borrowed element but not dropping it?

查看:43
本文介绍了有什么方法可以允许移动具有借入元素但不能删除它的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个容器:

use std::ptr::NonNull;

struct Container {
    data: NonNull<u8>,
}

impl Container {
    fn new() -> Container {
        todo!()
    }
    fn borrow_some_heap_data<'a>(&'a self) -> &'a u8 {
        todo!()
    }
    fn borrow_some_heap_data_mut<'a>(&'a mut self) -> &'a mut u8 {
        todo!()
    }
}

impl Drop for Container {
    fn drop(&mut self) {
        todo!()
    }
}

fn main() {
    let container = Container::new();
    let data = container.borrow_some_heap_data(); // or mut

    {
        let container = container; // move

        // This is safe because the move is a memcpy and the heap data doesn't change.
        println!("{}", *data);
    }

    // This is not safe because the container has been dropped
    // println!("{}", *data);
}

error[E0505]: cannot move out of `container` because it is borrowed
  --> src/main.rs:30:25
   |
27 |     let data = container.borrow_some_heap_data(); // or mut
   |                --------- borrow of `container` occurs here
...
30 |         let container = container; // move
   |                         ^^^^^^^^^ move out of `container` occurs here
...
33 |         println!("{}", *data);
   |                        ----- borrow later used here

移动容器是安全的,即使有引用也是如此.但是,丢弃它是不安全的.有什么方法可以在Rust中表达这一点,允许移动但不允许 drop s?

Moving the container is safe even if there are references. Dropping it, however, is not safe. Is there any way to express this in Rust, to allow moves but not drops?

data .

推荐答案

不,在安全的Rust中无法做到这一点;编译器不够智能/没有语法可以区分容器的生存期和元素的生存期.

No, there is no way of doing this in safe Rust; the compiler is not intelligent enough / there's no syntax to distinguish the container's lifetime from the lifetimes of the elements.

来自为什么不能在同一结构中存储值和对该值的引用?:

在一种特殊情况下,寿命跟踪过分热心:当您将某些东西放在堆上时.当您使用例如, Box< T> .在这种情况下,移动的结构包含一个指向堆的指针.指向的值将保持不变稳定,但指针本身的地址将移动.在实践中,没关系,因为您总是跟随指针.

There is a special case where the lifetime tracking is overzealous: when you have something placed on the heap. This occurs when you use a Box<T>, for example. In this case, the structure that is moved contains a pointer into the heap. The pointed-at value will remain stable, but the address of the pointer itself will move. In practice, this doesn't matter, as you always follow the pointer.

这篇关于有什么方法可以允许移动具有借入元素但不能删除它的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆