Re: Guarantee of side-effect free assignment
On Oct 7, 9:24 am, jdenn...@acm.org (James Dennett) wrote:
Alf P. Steinbach wrote:
[...]
This, however, while I would like it to be true, while it is what one
intuitively expect, I can find no such guarantee in the standard. It
seems the compiler is free to rewrite
p = new S();
as
p = operator new( sizeof( S ) );
new( p ) S();
What would grant the compiler freedom to deviate in such an
observable way from the semantics of the abstract machine (in
which, I hope it is clear, the rhs of an assignment is evaluated
before its result -- if there is one -- is assumed to be known).
The lack of any sequence points, and the fact that calling the
constructor is a "side effect"; the "value" of the expression
may be known before it is called.
provided S doesn't define operator new (in which case that one would
have to be used for the allocation, but that's just details).
Scott Meyers and Andrei Alexandrescu have assumed[1] that the above
rewrite can only occur when the compiler can prove that S() doesn't
throw; however, they give no formal justification for this assumption.
I think the regular notions of expression evaluation cover
it; rewriting is allowed to some extent by the "as-if" rule,
but nothing grants license to make such observable changes
to the notion of evaluating an assignment f(a)=g(b). The
assignment can't take place until the result of evaluating
g is known -- and if g throws, then it *has* no result.
In something like:
j = ++ i ;
there is (intentionally) definitely no requirement that the
change in i's value (a side effect) occur before the assignment
to j. And the C standard was carefully worded to make any code
which could detect the difference undefined behavior. In the
case of operator new, in C++, we have a lot more complex side
effects---the constructor is called---but basically, up to a
point, the same rule applied: there was no way a conforming
program could tell, so it didn't matter. Exceptions change
that. Suppose, in the expression above, the modification to the
value of i *could* trigger an exception. Would you say that we
are guaranteed that j is unmodified if this exception occured?
I don't think so.
The real problem, of course, is that exceptions really require
specifying the order of evaluation much more strictly. Which I
very definitely favor, but which is a road I don't think the
committee wants to take.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]