连续调用临时对象的方法

successively calling temporary object's methods

本文关键字:方法 临时对象 调用 连续      更新时间:2023-10-16

是否符合以下代码标准:

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成员函数,其中包括赋值操作符。

是的,临时变量的生存期延伸到整个表达式的末尾(除非通过绑定到引用来扩展)。