Re: Order of execution in an expression: thread safety
On Jan 11, 11:07 am, borsa...@thphys.uni-heidelberg.de wrote:
coming from C, I understand that the order of evaluation of
subexpressions is unspecified, unless there is a sequence
point somewhere in between. Suppose A,B,C,D are instances of a
class X with an overloaded operator+ and operator*, that
create and return temporary objects of the same type.
Just a reminder: user defined operator+ and operator* are
function calls, which introduce sequence points.
1) Is the compiler allowed to optimize using threads when compiling
the following statement?
X result=A*B+C*D;
Or from the developer's point of view, does the operator* have to
be reentrant?
(I am tempted to use static objects instead of creating
temporary ones, you can tell me if that's a bad design.)
operator* doen't have to be reentrant, in the sense that once
the compiled code enters the function, nothing else in calling
expression will take place until you return from the function.
I don't see what that buys you, however. You still can't use a
static object for the return value, since the compiler will
obviously call operator* twice in the above (with two return
values), before calling operator+ And within the function,
there's no advantage of using static variables either.
If you're worried about too many overly large objects, the usual
solution is to use some sort of proxy classes---today, most
often, a set of class templates, but a set of classes all
deriving from a common base works just as well. (At least in
theory---if the total becomes so complex that the compiler
refuses to inline it, then the presence of virtual function
calls can seriously interfere with the compiler's ability to
optimize.) Try searching the web for "template expressions".
2) Is the time of calling the destructors specified? My system
destroys the temporary objects after
the construction of 'result'.
That's guaranteed. In most cases, the compiler destroys the
temporaries at the end of the full expression. If the
expression is an initializer in a definition, however, this
destruction is deferred until the defined object is constructed.
--
James Kanze (GABI Software) mailto:james.kanze@gmail.com
Conseils en informatique orient=EF=BF=BDe objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=EF=BF=BDmard, 78210 St.-Cyr-l'=EF=BF=BDcole, France, +33 (0)1 30 2=
3 00 34