如何确保对象的寿命不会超过其工厂
假设我有一个对象工厂:
struct Object;
struct Factory;
impl Object {
pub fn new() -> Object { Object{} }
}
impl Factory {
pub fn new() -> Factory { Factory{} }
pub fn create() -> Object { Object::new() }
}
如何确保工厂创建的对象不会比工厂寿命更长?换句话说,如何使这样的代码无法编译:
let factory = Factory::new();
let object = factory.create();
drop(factory); // Some kind of lifetime compile error
只要编译器知道发生了什么,就可以随意使用任何包装器/容器来跟踪所有内容。我自己尝试过返回很多不同的东西,包括 &RefCell
Lets say I have a factory of objects:
struct Object;
struct Factory;
impl Object {
pub fn new() -> Object { Object{} }
}
impl Factory {
pub fn new() -> Factory { Factory{} }
pub fn create() -> Object { Object::new() }
}
How can you ensure that objects created by the factory do no outlive the factory? In other words, how to make code like this not compile:
let factory = Factory::new();
let object = factory.create();
drop(factory); // Some kind of lifetime compile error
Feel free to use any wrappers/containers to keep track of everything, as long as the compiler knows that something's up. I have tried returning a lot of different things myself, including &RefCell<Object>
, but I always run into a wall and end up starting over.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rust 有一个生命周期/借用检查机制,以确保引用不会比被引用对象的寿命更长。您可以使用相同的原则来保证
对象
的寿命不会超过其工厂
的寿命。您所需要的只是Object
有一个绑定到Factory
的生命周期注释,如下所示(游乐场):Rust has a lifetime/borrow-checking mechanism to ensure references do not outlive the referenced object. You can use the same principles to guarantee that
Object
s do not outlive theirFactory
. All you need is forObject
to have a lifetime annotation that is bound to theFactory
like so (playground):在对象中保留对工厂的引用。这将使得在删除(或改变)
factory
的未完成对象之前不可能删除它。下面的代码失败并出现生命周期错误,因为它试图使
object
超出factory
的生存期:Keep a reference to the factory in the object. This will make it impossible to drop (or mutate)
factory
before its outstanding objects are dropped.The code below fails with a lifetime error because it tries to make
object
outlivefactory
: