函数调用中的临时对象何时在 Rust 中被丢弃?

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

Rust 函数调用中临时对象的作用域规则是什么?我真正感兴趣的是执行以下操作是否安全:

fn foo() -> CString { /* */ }
fn bar(arg: *const libc::c_char) { /* */ }

bar(foo().as_ptr())

我创建了最小示例,它按我想要的方式工作——对象在函数调用后被删除 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());
}

我可以依赖这种行为吗?

rust reference 中,在 'Temporary Lifetimes' 下,它说:

... 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

在您的案例中,最内层的封闭语句是对 bar( ) 的调用。同一部分中有与您的情况非常相似的示例。

如果不是这种情况,编译器将不会编译您的代码。