Re: local static variable (just a curiosity, btw)
On Sat, 28 Apr 2007 20:58:42 +0300, "Alex Blekhman" <xfkt@oohay.moc> wrote:
static volatile DWORD x; // = 0 is redundant; deleted the
const
if (x == 0)
x = perform::computation();
return x;
Practically speaking, I think you could even delete the
"volatile"
specifier under these extreme conditions
(perform::computation thread-safe
and depends on no data any thread can be using). I mean,
it would take a
very smart compiler to eliminate the x test...
Yes, you're right. As far as multiple (and parallel) calls
to `perform::computation' are OK, then there shouln't be any
problem. Moreover, the controlling expression within `if' is
a sequence point. So even if a compiler is really smart,
nevertheless it isn't allowed to eliminate condition check.
Call the code above the body of a function "get_constant", then...
It would first have to prove that perform::computation returns a constant
value, and then it would have to determine the sequence of calls to
get_constant for the whole program. The latter part is not going to be
possible in general, and inside a function that makes multiple calls to
get_constant, it isn't going to matter, as long as it doesn't elide the
test for the first such call by that function. So it's only extreme
paranoia that would cause me to leave volatile in, which I would do, but
I'd still feel like I was making a magic incantation of sorts, which is not
a bad thing, because volatile and multithreading rarely intersect in valid
ways.
--
Doug Harrison
Visual C++ MVP