Re: static member initialization
"Frank Neuhaus" <fneuhaus@uni-koblenz.de> wrote in message =
news:gamifk$5m8$1@cache.uni-koblenz.de...
It seems from the above that
* Only someFunc (plus possibly functions called by someFunc) uses =
the
var.
Thats not correct unfortunately. The static variable is used to make a =
list
of all classes of a certain type.
* The use of a pointer is not from any particular reason, i.e. it's =
not
in
order to circumvent ordinary lifetime rules (destruction order).
The pointer was an attempt to trick the initialization order thing. If =
the
vector is not a pointer, and it is accessed before it is initialized, =
it
actually crashes - with the pointer at least it doesnt crash (though =
im
assuming it is definately not a correct solution).
I have given this a bit more thought and came up with this:
class MyClass
{
public:
static void myfunc();
private:
static std::vector<int>& getvec() { static std::vector<int> v; =
return
v; };
};
}
now myfunc can simply do
void MyClass::myfunc()
{
std::vector<int>& myvec=getvec();
// do sth with myvec
}
That seems like a viable method to circumvent the problem, right?
Yes, but there is still a problem when the program ends.
How do you make sure that the static vector v is not destructed too =
early?
If myfunc is used in the destructor of another static object,
it might be that v has been destructed already.
Therefore I use a similar method, but the code of getvec looks like
{
static std::vector<int> *v = new std::vector<int>;
return *v;
}
The disadvantage of this is that v is never destructed.
Which in many cases does not harm.