何时在Rust中删除功能调用中的临时对象?
在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 rust routs commution ,在'临时生活'下,它说:
在您的情况下,最内置的语句是呼叫
bar()
。在同一部分中有一些与您的案件非常相似的示例。如果不是这种情况,编译器不会编译您的代码。
In the rust reference, under 'Temporary Lifetimes', it says:
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.