What are scoping rules for temporary objects inside function call in Rust? What I actually interested in whether it is safe to do following:
fn foo() -> CString { /* */ }
fn bar(arg: *const libc::c_char) { /* */ }
bar(foo().as_ptr())
I created minimal example, and it works as I want -- object is dropped after function call returns.
struct Bar {
pub x: u32
}
impl Bar {
pub fn new(x: u32) -> Self {
println!("New Bar made!");
Bar { x }
}
pub fn extract(&self) -> u32{
self.x
}
}
impl Drop for Bar {
fn drop(&mut self) {
println!("Bar dropped!");
}
}
pub fn foo(arg: u32) {
println!("Function called with arg = {}", arg);
}
fn main () {
foo(Bar::new(12).extract());
}
Can I rely on this behaviour?
In the rust reference, under 'Temporary Lifetimes', it says:
... the lifetime of temporary values is typically
- the innermost enclosing statement; the tail expression of a block is considered part of the statement that encloses the block, or
The innermost enclosing statement in your case is the call to bar( ). There are examples in the same section very similar to your case.
The compiler would not have compiled your code if this were not the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With