简体   繁体   English

特征 object 参考的寿命

[英]life time of a trait object reference

With FooClass that implements FooTrait , and Bar that takes the reference of a FooTrait object, the code is working:使用实现FooTraitFooClass和引用FooTrait object 的Bar ,代码正在运行:

trait FooTrait {
    fn print(self);
}

struct FooClass {}

impl FooTrait for FooClass {
    fn print(self) {
        println!("It's a Foo");
    }
}

struct Bar<'a> {
    foo: &'a (dyn FooTrait),
}

impl<'a> Bar<'a> {
    fn new(_foo: &'a (dyn FooTrait)) -> Bar<'a> {
        Bar { foo: _foo }
    }
}

fn main() {
    let foo = FooClass {};
    let bar = Bar::new(&foo);
    println!("hello world");
}

But for但对于

struct Bar<'a> {
    foo: &'a (dyn FooTrait),
}

impl<'a> Bar<'a> {
    fn new(_foo: &'a (dyn FooTrait)) -> Bar<'a> {
        Bar { foo: _foo }
    }
}

I have also seen they are written as我也看到他们写成

struct Bar<'a> {
    foo: &'a (dyn FooTrait + 'a),
}

impl<'a> Bar<'a> {
    fn new(_foo: &'a (dyn FooTrait + 'a)) -> Bar<'a> {
        Bar { foo: _foo }
    }
}

I think I understand that struct Bar<'a> { foo: &'a (dyn FooTrait + 'a), } says, foo should live at least as long as Bar so that reference stay valid.我想我理解struct Bar<'a> { foo: &'a (dyn FooTrait + 'a), }说, foo应该至少和Bar一样长,这样引用才能保持有效。 But this explains only Bar<'a> and foo: &'a , that I don't see what does + 'a do after dyn FooTrait in the parentheses.但这仅解释了Bar<'a>foo: &'a ,我看不到+ 'a在括号中的dyn FooTrait之后做了什么。 Also, removing +'a doesn't seems to break the program.此外,删除+'a似乎不会破坏程序。 Can someone explain to me the purpose?有人可以向我解释目的吗?

The + 'a says that not only does the concrete type need to implement FooTrait , but it also may not itself contain references that live shorter than 'a . + 'a表示不仅具体类型需要实现FooTrait ,而且它本身也可能不包含比'a更短的引用。

Consider:考虑:

struct FooWithRefs<'b> { reff: &'b i32, }
impl <'b> FooTrait for FooWithRefs<'b> { ... }

fn main() {
    let i = 100;
    let foo = FooWithRefs { reff: &i };
    let bar = Bar::new(&foo);
    println!("hello world");
}

The compiler needs to know that not only does foo not disappear during the lifetime of bar , but also that nothing foo itself references goes out of scope.编译器需要知道,不仅foobar的生命周期内不会消失,而且foo本身引用的任何内容都不会超出 scope。 The + 'a condition ensures this. + 'a条件确保了这一点。

(I can't think of a way to write an example that violates this condition that won't also violate the mere creation of the FooWithRefs though.) (我想不出一种方法来编写一个违反此条件的示例,但也不会违反FooWithRefs的单纯创建。)

I don't know the exact semantics of omitting the lifetime bound, though.不过,我不知道省略生命周期限制的确切语义。 Trying it out suggests that it implicitly uses the same bound.尝试一下表明它隐含地使用了相同的界限。

See it on the playground 在操场上看

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

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