简体   繁体   English

如何创建一次性可变引用?

[英]how can I create a throwaway mutable reference?

I'm trying to wrap a vector to change its index behaviour, so that when an out of bounds access happens, instead of panicking it returns a reference to a dummy value, like so:我试图包装一个向量来改变它的索引行为,这样当发生越界访问时,它不会恐慌,而是返回对虚拟值的引用,如下所示:

use std::ops::Index;

struct VecWrapper(Vec<()>);

impl Index<usize> for VecWrapper {
    type Output = ();
    fn index(&self, idx: usize) -> &() {
        if idx < self.0.len() {
            &self.0[idx]
        } else {
            &()
        }
    }
}

which works just fine for the implementation of Index, but trying to implement IndexMut the same way fails for obvious reasons.这对于 Index 的实现来说工作得很好,但是由于显而易见的原因,尝试以相同的方式实现 IndexMut 失败了。 the type in my collection does not have a Drop implementation so no destructor needs to be called (other than freeing the memory).我的集合中的类型没有 Drop 实现,因此不需要调用析构函数(释放内存除外)。

the only solution I can think of is to have a static mutable array containing thousands of dummies, and distributing references to elements of this array, this is a horrible solution though it still leads to UB if there are ever more dummies borrowed than the size of the static array.我能想到的唯一解决方案是拥有一个包含数千个虚拟对象的 static 可变数组,并分发对该数组元素的引用,这是一个可怕的解决方案,但如果借用的虚拟对象数量超过了大小,它仍然会导致 UB static 数组。

Give the wrapper an additional field that's the dummy.为包装器提供一个附加字段,即虚拟字段。 It's got the same lifetime restrictions, and so can't be aliased.它具有相同的生命周期限制,因此不能使用别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM