什么时候临时销毁? [英] When is a temporary destructed?
问题描述
直到现在,我都认为在生成它的语句的评估结束时会破坏一个临时对象.
Up until now, I assumed that a temporary was destructed at the end of the evaluation of the statement that had spawned it.
但是,使用临时对象初始化struct
的字段时,似乎出现了异常.
However, it appears that there is an exception made when using a temporary to initialize the field of a struct
.
PeterHall 帮助提供了一个简单的代码示例,说明了差异 在对他的回答的评论中,我已经简化了有点复杂:
PeterHall helpfully provided a simple code sample illustrating the difference in a comment to his answer, which I've simplified complicated a bit:
struct Wrapper<'a> {
cmd: &'a Cmd<'a>,
}
struct Cmd<'a> {
args: &'a Option<String>,
}
impl <'a> Cmd<'a> {
fn new(args: &'a Option<String>) -> Cmd<'a> {
Cmd {
args: args,
}
}
}
pub fn main() {
// OK
let cmd = Cmd {
args: &None,
};
// OK
let cmd = Wrapper {
cmd: &Cmd {
args: &None,
}
};
// Lifetime error
let cmd = Some(Cmd {
args: &None,
});
// Lifetime error
let cmd = Cmd::new(&None);
}
那么,临时销毁的确切规则是什么?
So, what is the exact rule for when a temporary is destructed?
推荐答案
我们先看看第二个失败的行:
Let's look at the second failing line first:
let cmd = Cmd::new(&None);
&None
创建一个具有单行生命周期的临时文件.Cmd::new
返回一个具有相同生命周期的 Cmd
.然后我们尝试使用 let
将该临时变量存储在一个变量中.
&None
creates a temporary with a lifetime of the single line. Cmd::new
returns a Cmd
that has the same lifetime. Then we have attempt to store that temporary in a variable with let
.
当一个临时右值被创建并分配给一个 let 时声明,但是,临时创建的生命周期为代替封闭块...
When a temporary rvalue is being created that is assigned into a let declaration, however, the temporary is created with the lifetime of the enclosing block instead...
它试图增加 Cmd
临时文件的生命周期,但这取决于 &None
临时文件的生命周期,并且由于该临时文件实际上并未存储在 let
(关于持续到语句结束的临时规则的例外)中,它的生命周期小于 cmd
的生命周期并且你会得到一个生命周期错误.
It tries to increase the lifetime of the Cmd
temporary, but that depends on the lifetime of the &None
temporary, and since that temporary isn't actually stored in a let
(the exception to the rule about temporaries lasting until the end of the statement), its lifetime is less than the lifetime of cmd
and you get a lifetime error.
直接结构语句有效,因为 let
生命周期适用于结构及其成员.
The direct struct statements work, because the let
lifetime applies to the struct and its members.
它对 Some
(一个枚举)不起作用的事实对我来说似乎是一个错误(或者至少是一个缺失的功能).
The fact that it doesn't work for Some
(an enum) seems like a bug to me (or at least a missing feature).
这篇关于什么时候临时销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!