| re: static data member initialization
On Thu, 09 Feb 2006 10:06:19 -0800, Axter wrote:
[color=blue]
> Victor Bazarov wrote:[color=green]
>> Mike - EMAIL IGNORED wrote:[color=darkred]
>> > MyClass
>> > {
>> > //I have a static member method:
>> > void static myMethod();
>> > //and a static data member:
>> > static MyType myData;
>> > };
>> >
>> > //In the .cpp file:
>> > void MyClass::myMethod()
>> > {
>> > if (myData == myInitialValue)
>> > ...
>> > }
>> > //and below, in the same file:
>> > MyType MyClass::myData = myInitialValue;
>> >
>> > Can I rely on initialization in time for the if
>> > statement? Chapter and verse?[/color]
>>
>> Objects with static storage duration (static data members included)
>> defined outside of any function scope are initialised before 'main'
>> is called. So, if youre 'myMethod' function is called in the course
>> of normal program execution, 'myData' will have been initialised.
>> If the 'myMethod' function is called during another static object
>> initialisation, all bets are off, unless that object is declared
>> _after_ 'myData' in the _same_ translation unit.
>>[/color]
>
> Actually, the complete answer is a little more complicated than that.
> If MyType is a POD type, then it's garanteed to be initialized before
> any global complex (non-POD) type. This includes static data members.
> Even if not in same translation unit.
> You can not ganrantee the order of initialization if MyType is a
> non-POD type, and it's access from a global object's constructor that
> is in a different translation unit.
>
> An easy work around method for this is to create the object as a static
> local variable within a static function.
>
> class MyClass
> {
> void static myMethod();
> //Replace above with following:
> inline static MyType& GetMyData(){static MyType myData;}
> };
>
> Now your variable is garanteed to be initialized IAW C++ standard when
> you call it.
> However, if it's called from a global object's destructor, you will
> still have issues with order of destructor.[/color]
Interesting. I was using the static method you mention, but I
had several such variables, and I wondered of it was really
necessary. Since they are all POD, I see that it is not.
By the way, when you say POD, can I take this literally,
thereby including POD structs?
Also, can anyone point to the sections in the standard that
one would read to draw these conclusions?
Thanks for your comments.
Mike. |