KAction
KAction

Reputation: 625

When exactly temporary object in function call is dropped in Rust?

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?

Upvotes: 2

Views: 383

Answers (1)

harmic
harmic

Reputation: 30577

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.

Upvotes: 2

Related Questions