|
|
|
|
|
by kam
4155 days ago
|
|
Yeah, it's unclear what he's talking about there. Normally when a function allocates a new object, it would want to return it by move (transferring ownership), rather than by reference. That doesn't involve any lifetimes. fn make_a_foo() -> Box<Foo> {
Box::new(Foo { a: 5 })
}
If the function allocated memory and only returned a borrowed reference, who would be responsible for freeing it? Yes, Rust will make you stop and think there, as it enforces memory safety.In cases where it does make sense to return a reference to a new object, like allocating from an arena, the lifetime ('a) of the returned reference will be the same as the lifetime of the arena. fn new_from_arena<'a>(arena: &'a TypedArena<Foo>) -> &'a mut Foo {
arena.alloc(Foo { a: 5 })
}
But Rust can infer the lifetime, so that can be shortened to: fn new_from_arena(arena: &TypedArena<Foo>) -> &mut Foo {
arena.alloc(Foo { a: 5 })
}
|
|