Re: Guarantee of side-effect free assignment
Alf P. Steinbach wrote:
* James Dennett:
Alf P. Steinbach wrote:
From discussions in [comp.lang.c++] and [comp.lang.c++.moderated], as
well as articles on the net about concurrency in C++, I'm reasonably
sure that given
#include <iostream>
#include <ostream>
struct S { S(){ throw 123; } int foo(){ return 666; } };
int main()
{
S* p = 0;
try
{
p = new S();
}
catch( ... )
{}
if( p ) { std::cout << p->foo() << std::endl; }
}
there is no guarantee that this code will not end up in a call to
p->foo() with an invalid pointer p, i.e., that might well happen.
Surely that couldn't have been the committee's intention?
I wouldn't imagine so.
Thank you James, that's what I'm thinking too.
Why isn't assignment treated as a function call?
It doesn't need to be. The assignment cannot occur until the
new value is known, which means that the "new" operator
has returned its result, which means that the object has been
constructed. If the constructor throws, there's no value
from "new" above, and the assignment cannot occur; p will
remain null.
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).
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.
-- James
---
[ 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 ]