Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

successively calling temporary object's methods [duplicate]

Tags:

c++

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?
like image 937
feverzsj Avatar asked Dec 26 '22 09:12

feverzsj


2 Answers

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)

like image 74
rici Avatar answered Jan 12 '23 14:01

rici


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).

like image 40
Cheers and hth. - Alf Avatar answered Jan 12 '23 13:01

Cheers and hth. - Alf