Re: How to write a library with a static object?
John Harrison wrote:
Jeroen wrote:
OK, thanx. Very helpfull to read the link. Let me try a better
construction: if I go back to my code (yet to write...), then I have:
* class A that's available to the user
* class B that is used 'underwater', but only if the user does
something with class A
* a list for objects of class B (only accessed if the user does
something with class A...)
So maybe I am safe if I put the list as a static member of class A?
class B {
int blah;
};
class A {
private:
static list<B> my_list;
static void put_B_in_the_list(const B& b);
static B& find_B_in_the_list(int blah);
int more_blah;
};
Given the fact that the list is only accessed if the user of the
library uses class A, this should prevent the init fiasco described in
the link you gave?
Thanx again,
Jeroen
No, if your user attempts to use class A in the construction of a global
object there is no guarantee that my_list will have been constructed.
You only get that guarantee by putting my_list as a static in a global
function as shown in the FAQ.
john
Excuse me, but does anyone know why this fiasco even exist? Why is
there not some dependency mechanism in place? Or something like the
static local object being constructed when the control flows to them (as
opposed to over them)?
One other thing. In that FAQ we have Fred defined as so:
// File x.cpp
#include "Fred.h"
Fred& x()
{
static Fred* ans = new Fred();
return *ans;
}
Why is it not defined like this:
// File x.cpp
#include "Fred.h"
Fred& x()
{
static Fred ans;
return &ans;
}
It looks to me that the compilers are built pretty flimsily.
Adrian