When是一个临时的,用作已销毁的命名对象的初始值设定项

When is a temporary used as an initializer for a named object destroyed?

本文关键字:对象 一个 When      更新时间:2023-10-16

在"C++编程语言(第三版)"第255页:

临时可以用作常量引用或命名对象的初始值设定项。例如:

void g(const string&, const string&);
void h(string& s1, string& s2)
{
   const string& s = s1+s2;
   string ss = s1+s2;
   g(s, ss);  // we can use s and ss here
}

这很好。当"其"引用或命名对象超出范围时,临时对象将被销毁。

他是说s1+s2创建的临时对象在ss超出范围时被销毁吗?它不是一被复制初始化为ss就被销毁了吗?

代码中唯一的临时代码是s1 + s2。第一个绑定到常量引用s,因此它的寿命延长到s的寿命。代码中没有其他内容是临时的。特别是,sss都不是临时变量,因为它们显然是命名变量

第二个s1 + s2当然也是临时的,但它在行的末尾死亡,只用于初始化ss

更新:也许有一点值得强调:在最后一行g(s, ss);中,重点是s是一个完全有效的引用,而它不是您可能预期的悬挂引用,这正是因为绑定到常量引用的临时性的生命期扩展规则。

两者都为true,因为创建了两个临时性:

//creates a temporary that has its lifetime extended by the const &
const string& s = s1+s2;
//creates a temporary that is copied into ss and destroyed
string ss= s1+s2;
相关文章: