When是一个临时的,用作已销毁的命名对象的初始值设定项
When is a temporary used as an initializer for a named object destroyed?
在"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
的寿命。代码中没有其他内容是临时的。特别是,s
和ss
都不是临时变量,因为它们显然是命名变量。
第二个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;
相关文章:
- 如何返回一个类的两个对象相加的结果
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- PyRun_String返回一个NoneType对象
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 从多个源构造一个对象,包括一个对象向量
- 如何在没有数据拷贝的情况下从指针创建一个Eigen VectorXd对象
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 检查哪个对象调用了另一个对象的对象方法
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 返回一个带有 std::move 的对象并链接函数
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问可调用对象 一个 boost::thread 是用来构造的
- 如何自动将 FLTK 的Fl_Input对象一个堆叠在另一个下面