[comp.lang.c++] undesired optimiztion

jean@paradim.UUCP (Jean Pierre LeJacq) (08/25/90)

In article <883@zinn.MV.COM>, mjv@objects.mv.com (Michael J. Vilot) writes:
> ...
> The Timer object `t' is only active in the inner block.  Of course, the
> object is apparently never used, so I may get into trouble with those
> building aggressively-optimizing compilers. ...

C++ uses the keyword volatile to provide a hint to the compiler
to avoid aggresive optimization involving an object. Since it is
only a hint, I'm not sure how portable a solution this would be.

steve@taumet.com (Stephen Clamage) (08/28/90)

jean@paradim.UUCP (Jean Pierre LeJacq) writes:

|In article <883@zinn.MV.COM>, mjv@objects.mv.com (Michael J. Vilot) writes:
|> ...
|> The Timer object `t' is only active in the inner block.  Of course, the
|> object is apparently never used, so I may get into trouble with those
|> building aggressively-optimizing compilers. ...

|C++ uses the keyword volatile to provide a hint to the compiler
|to avoid aggresive optimization involving an object. Since it is
|only a hint, I'm not sure how portable a solution this would be.

E&S section 3.5:
	"A named local object may not be destroyed before the end
	of its block nor may a local named object of a class with
	a constructor or a destructor with side effects be
	eliminated even if it appears to be unused."

So a correct compiler, even an agressively-optimizing one, may not
omit (or move) the constructor/destructor Mike Vilot mentions.

As Jean Pierre mentions, "volatile" is not guaranteed to do what you want,
as its semantics are explicitly implementation-dependent (section 7.1.6).
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com

mjv@objects.mv.com (Michael J. Vilot) (09/03/90)

>From Steve Clamage:
> E&S section 3.5:
>	"A named local object may not be destroyed before the end
>	of its block

Note the word `named' in this phrase, it's important.
I had a fragment of code that was too clever by half:
	{
	  Lock(*this);    // constructor acquires lock
	  // some action
	}                 // destructor releases lock
g++ optimized away the unnamed temporary, calling the destructor
immediately rather than at the end of the block.  This is perfectly
legal, and was solved by explicitly naming the Lock object.
--
Mike Vilot,  ObjectWare Inc, Nashua NH
mjv@objects.mv.com  (UUCP:  ...!decvax!zinn!objects!mjv)