Re: Question about a static vector<*A> in class A
Ondra Holub schreef:
But you cannot test on 'vector_ptr' because it may not be initialized,
just like the code I had originally...
Static data (which is not defined in any function) is automatically
initialized to 0, so you can test it for 0 and initialize it. This is
valid only for static data defined in any class/struct or in global
scope.
So code could look like:
-- cut here --
#include <cstdlib>
#include <iostream>
class A
{
public:
~A()
{
std::clog << "A::~A()\n";
}
// Access method for static data
static A& GetInstance()
{
if (instance == 0)
{
instance = new A();
if (atexit(&A::CleanUp) != 0)
{
std::cerr << "Cannot register CleanUp function!\n";
exit(1);
}
}
return *instance;
}
void Method()
{
std::cout << "A::Method() called\n";
}
private:
A()
{
std::clog << "A::A()\n";
}
static void CleanUp()
{
delete instance;
}
static A* instance;
};
A* A::instance;
int main()
{
std::cout << "Start of main\n";
A::GetInstance().Method();
A::GetInstance().Method();
std::cout << "End of main\n";
}
-- cut here --
And will produce following output:
-- cut here --
Start of main
A::A()
A::Method() called
A::Method() called
End of main
A::~A()
-- cut here --
Sorry, but I'm lost here... In my original post I coded something like:
class A {
static std::vector<A> my_vector;
// rest of class omitted
};
And you replied:
"If you place your static data inside a class as private data, you
still have no guaranty, that it will be initialized before usage,
because any public method of your class may be called during
initialization of other static stuff."
So I can understand the solution to put the static vector in a method of
class A (like I tried to give an example for in my last post). Or was
that attempt of me not correct?
In your example you have:
class A {
static A* instance; // Vector or just A* does not matter here....
// rest of class omitted
};
and suddenly it is OK to use the value of 'instance' in a public method
("if (instance == 0)" in "GetInstance()"). I don't see differences in
the two pieces of code regarding to the possible crash... If you rely on
the fact that 'instance' is initialized when you first use it in a
public method, why can't you rely on the same initialization for
'my_vector'?
Jeroen