Victor Bazarov wrote:
> Anonymous wrote:
>
>>I have a class (classA) that requires initialisation ONCE. It also
>>provides static methods that depend on various variables etc to have
>>been correctly initialised.
>>
>>Some sample code to explain the scenario:
>>
>>class ClassA
>>{
>>public:
>> ~ClassA();
>>static ClassB * fetchB();
>>static ClassC * fetchC();
>>
>>private:
>>ClassA();
>>static int dummy ;
>>};
>>
>>
>>//Impl
>>namespace
>>{
>> int MyInitStuf(){ return 42 ;} //assume this allocs memory
>> void Cleanup(); //used to clean up previously allocd mem
>>};
>>
>>static int ClassA::dummy = MyInitStuf();
>>
>>
>>I have two questions re the code above:
>>
>>1). Is the dummy variable GUARANTEED to have been initialised already
>>if I call one of the static methods (or are the satic variables first
>>initialised when an INSTANCE is created ?
>
>
> No. What if you call one of the static member functions in another
> static object's constructor? If the objects are in difference TU,
> you have "static order initialisation fiasco", see FAQ. There is no
> connection between creating an instance of a class and the class'
> static data members, unless you create such a connection.
>
>
>>2). Supposing that the MyInitStuf() function allocates memory etc, how
>>can I enforce deallocation of the memory allocated during
>>initialisation ? - i.e. at what point do I call Cleanup() ?
>
>
> Your 'dummy's destructor should probably do that. And since it's an int,
> and you can't provide a destructor for it, you could have a companion
> object that when destructed would access 'dummy' and free the memory.
>
> V
This was going to be the next step forward - i.e. wrap up all the
initialisation paraphenalia and vaiables in a struct or class data type,
and declare/define a class member of that type in ClassA
However, according to wht you wrote earlier: "There is no connection
between creating an instance of a class and the class' static data
members, unless you create such a connection."
I'm not sure how even that (i.e. declaring dummy of type
'MyWrapperObject' gets around this unless - since mere invocation of the
static methods does not mean that the static variable has been defined -
hold on, but I am defining it at compile time - so maybe this is not an
issue? (I AM getting confused).