先后调用临时对象的方法

时间:2014-05-09 05:46:55

标签: c++

遵循以下代码标准:

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?

2 个答案:

答案 0 :(得分:7)

完全安全。

见第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)

答案 1 :(得分:3)

原始代码:

struct Temp
{
    Temp& op1() { ...; return *this; }
    Temp& op2() { ...; return *this; }
    // more op...
}

由于缺少最终分号,此代码不符合标准且无法编译。

它说明了发布实际代码的重要性。


也就是说,成员函数,甚至非const成员函数,都可以在临时类类型对象上调用,包括赋值运算符。

是的,临时的生命周期延伸到完整表达式的结尾(除非通过绑定到引用进行扩展)。