何时在Rust中删除功能调用中的临时对象?

发布于 2025-01-24 17:07:11 字数 686 浏览 3 评论 0原文

在RUST中,功能中的临时对象的范围规则是什么?我对是否安全地进行以下操作感兴趣的是:

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

bar(foo().as_ptr())

我创建了最小的示例,并且它可以按照我的需求工作 - 函数调用返回后删除对象。

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());
}

我可以依靠这种行为吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

≈。彩虹 2025-01-31 17:07:11

rust routs commution ,在'临时生活'下,它说:

...临时值的寿命通常为

  • 最内在的封闭式陈述;块的尾巴表达被认为是包围块的陈述的一部分,或者

在您的情况下,最内置的语句是呼叫bar()。在同一部分中有一些与您的案件非常相似的示例。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文