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?
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With