连续调用临时对象的方法
successively calling temporary object's methods
是否符合以下代码标准:
struct Temp
{
Temp& op1() { ...; return *this; }
Temp& op2() { ...; return *this; }
// more op...
};
Temp().op1().op2()....; // safe or not? Which paragraph from ISO 12.2 qualifies it?
绝对安全。
它在第3段(§12.2, [class.temporary]
):
临时对象在(词法上)包含其创建点的完整表达式(1.9)求值的最后一步被销毁。
§1.9/10 ([intro.execution]
)定义full-expression:
完整表达式不是另一个表达式的子表达式。
,包括一个与你的问题有点相似的例子:
void f() {
if (S(3).v()) // full-expression includes lvalue-to-rvalue and
// int to bool conversions, performed before
// temporary is deleted at end of full-expression
{ }
}
引用和段落编号来自N3691, 2013年中期的c++草案,但它们已经几年没有改变了,它们可能会在c++ 1x中继续有效,甚至很可能在c++ 1y中(x≅4;y≅ 7)
原代码:
struct Temp
{
Temp& op1() { ...; return *this; }
Temp& op2() { ...; return *this; }
// more op...
}
由于缺少最后的分号,此代码不符合标准,因此无法编译。
它说明了发布真实代码的重要性。
也就是说,可以在临时类类型对象上调用成员函数,甚至是非const
成员函数,其中包括赋值操作符。
是的,临时变量的生存期延伸到整个表达式的末尾(除非通过绑定到引用来扩展)。
相关文章:
- 在不复制临时对象的情况下延长其生存期
- 为什么当我们有常量引用时创建临时对象?
- 程序如何'remember'临时对象?
- 返回对临时对象的引用
- 防止临时对象文件访问 MSVC 中的磁盘
- 是否可以在C++中移动临时对象的属性?
- 通过引用传递临时对象
- 临时C++对象是否为左值?
- 临时对象:术语澄清
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 临时对象有身份吗?
- 临时对象上的运算符重载
- 有什么方法可以延长C++中临时对象的生存期吗
- C 处理临时对象和数组的正确方法是什么
- C++矢量推回方法和临时对象创建
- 有多少种方法可以生成临时对象/不必要地调用构造函数
- 与const引用(方法链)相关联的临时对象的生命周期
- 将指向临时对象(在堆上)的指针传递给函数的方法
- 连续调用临时对象的方法
- 构造一个临时对象并调用一个返回指针的方法——安全吗?