Operadores de asignación compuestos con self en C++

To compute the square of 2.0, does this code

double a = 2.0;
a *= a;

have well defined behavior? And, equivalently, with all the other compound assignment operations and build-in types.

preguntado el 28 de mayo de 14 a las 13:05

why do you think it does not? -

I don't know. Something bugs me. Wouldn't the standard allow to implement a double, e.g., as two floats, and then the statement could become multiple machine instructions in which the first overwrites the memory location. And then the subsequent instructions produce garbage. -

Qué hay de malo en a = a * a? -

@dasblinkenlight I am just curious. Actually, I thought about using that expression, to be sure. -

@dasblinkenlight Too verbose. -

2 Respuestas

It's legal, because (C++11, §1.9/15): "The value computations of the operands of an operator are sequenced before the value computation of the result of the operator" or (C++03, §5/4): "Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored." (In a *= a, la a on the left side is accessed only to determine the value to be stored. And the evaluation of the a on the left side is a "value computation", without side effects.)

contestado el 28 de mayo de 14 a las 14:05

Sí lo es.

The only reason to believe the contrary would be an issue with puntos de secuencia, but that does not apply here.

1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

You only modify once, you are good.

contestado el 28 de mayo de 14 a las 13:05

The code is legal, but not for the reasons you quote. In particular, you ignore the sentence immediately following the one you quote, which says that you cannot (always) access the variable otherwise. The classical example would be something like f( a, ++ a ), Donde a is only modified once, but the expression still has undefined behavior. - james kanze

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.