Re: local static variable (just a curiosity, btw)
On Sat, 28 Apr 2007 17:12:03 +0300, "Alex Blekhman" <xfkt@oohay.moc> wrote:
"Tom Widmer [VC++ MVP]" wrote:
[...]
Under the hood, that is going to be something like:
//both are statically initialized:
static const bool __x_is_initialized = false;
static const DWORD x = 0;
//dynamic initialization:
if (!__x_is_initialized)
{
__x_is_initialized = true; //1
x = perform::computation(); //2
}
return x;
[...]
but then another proposal came out:
static const volatile DWORD x = perform::computation();
while (x == 0) {}
return x;
Would it work?
On VC2005, volatile has memory barrier semantics, and
writes to volatile DWORDs should be atomic, so I think it
will work, yes.
I don't think `volatile' specifier will help here. It is
because `volatile' guards `x' only, while placement of
internally generated `__x_is_initialized' is left to its own
devices (i.e., before `x'). With or without `volatile'
MSVC++2005 generates exactly the same code, which is akin to
that you posted.
That's a good point. Tom's alternative actually avoids that problem by
turning the dynamic initialization of x into static initialization, so that
there is no hidden __x_is_initialized variable to worry about:
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...
--
Doug Harrison
Visual C++ MVP