4

Is following code standard compliant:

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?
feverzsj
  • 169
  • 2
  • 14

2 Answers2

7

Totally safe.

It's in paragraph 3 (of §12.2, [class.temporary]):

Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

§1.9/10 ([intro.execution]) defines full-expression:

A full-expression is an expression that is not a subexpression of another expression.

and includes an example somewhat similar to your question:

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
  { }
}

The quotes and paragraph numbering come from N3691, the mid-2013 c++-draft, but they haven't changed in a few years and they will probably continue to be valid in C++1x and quite possibly even in C++1y (x≅4; y≅7)

rici
  • 234,347
  • 28
  • 237
  • 341
  • Presumably the standard references refer to C++11? Note that which standard is current, can have changed when some googler stumbles on this answer. – Cheers and hth. - Alf May 09 '14 at 06:26
  • Yes, C++11. It's a bit late here, but I'll fix it before the current standard is replaced or tomorrow, whichever comes first. – rici May 09 '14 at 06:43
  • In 2014, that's next year. Hopefully. – Cheers and hth. - Alf May 09 '14 at 09:18
  • @Cheersandhth.-Alf: Except in standards-land, 2014 is this year :) Still, it is possible that we'll see C++14 by 2015. I don't remember seeing any proposals which would renumber the cited paragraphs, but I haven't studied it all in huge depth. Anyway, edited the answer; if you have a more specific suggestion about how to cite the standard in the light of possible future changes, I'm all ears. – rici May 09 '14 at 15:41
  • +1 for the will to do properly. ;-) – Cheers and hth. - Alf May 09 '14 at 18:52
3

Original code:

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

Due to the lack of a final semicolon this code is not standard-compliant and will not compile.

It illustrates the importance of posting real code.


That said, yes, member functions, even non-const member funcitons, can be called on temporary class type objects, and that includes the assignment operator.

And yes, the lifetime of a temporary extends to the end of the full expression (unless extended by binding to a reference).

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331