static variables for non-constant expressions?

Steven Wawryk stevenw at acres.com.au
Mon Apr 11 17:59:42 PDT 2011


On 12/04/11 07:36, Simon wrote:
> On 11/04/2011 22:15, Stewart Gordon wrote:
>> On 11/04/2011 02:37, Jonathan M Davis wrote:
>> <snip>
>>>> I don't know the background of how static variables really work, so is
>>>> there a good reason why the first function can't work like the one
>>>> below
>>>> it?
>>>
>>> They have to be calculated at compile time so that ordering doesn't
>>> matter. If
>>> the order mattered, then you get into dependency problems or risk using
>>> undefined variables. Languages like C++ and Java have problems with
>>> that.
>> <snip>
>>
>> I recall reading that in C++, static variables are initialised on first
>> call. Which would have to mean that it does something like that
>> internally.
>>
>> But I might be imagining it. I'll have to experiment.
>>
>> Can you give an example of the dependency problems this might lead to?
>>
>> Stewart.
>
> In visual C++ all static vars with assignments/constructors get
> initialised by the CRT before main starts, though in an undefined order.
> Can lead to bugs if you use them carelessly.
>
> Pretty sure that applies to other compilers as well.
>

This is true for static "globals" and static members, but the C++ 
standard requires static locals (local to functions) to be initialized 
on first call.

It's a widely used idiom to avoid static initialization order issues to 
use functions that do nothing more than return a reference to a static 
local rather than use static globals directly.



More information about the Digitalmars-d-learn mailing list