Re: Mimicking Javas static class initializer in C++
In message <blargg.h4g-2910080412160001@192.168.1.4>, blargg
<blargg.h4g@gishpuppy.com> writes
In article <49062fa0$0$32668$9b4e6d93@newsspool2.arcor-online.net>,
Andreas Wollschlaeger <meister.possel@arcor.de> wrote:
Hi folks,
as the subject says, i'm a poor Java programmer trying to transfer some
of his wisdom into C++ world... here is what im trying to do this evening:
Java has a nifty feature called a static class initializer - something
like this:
public class Foo
{
private static Vector<Thing> xx;
static
{
xx = new Vector<Thing>(42);
for (int i=0; i < xx.size(); ++i)
xx.set(i, new Thing());
}
}
where the static{} block is called once (when the class is first used),
thus suitable for complex initializations of static members.
Now i would like to have this in C++, can this be done?
Trying to make as literal a translation here. This will initialize things
the first time a Foo object is created; if no Foo is ever created, this
initialization will never run.
// Foo.hpp
class Foo {
public:
Foo();
private:
static vector<Thing> xx;
}
// Foo.cpp
vector<Thing> Foo::xx;
Foo::Foo()
{
if ( xx.empty() )
{
xx = new Vector<Thing>(42);
???
xx is a vector, not a pointer.
for (int i=0; i < xx.size(); ++i)
xx [o] = new Thing();
.... and it contains Things, not pointers. You appear to be writing Java
here.
}
}
Here is a more general approach that separates the init code into its own
function:
// Foo.hpp
class Foo {
public:
Foo();
private:
static void first_use();
}
// Foo.cpp
void Foo::first_use()
{
// initialize statics
}
Foo::Foo()
{
static int call_once = (first_use(),0);
}
You could use a less-hacky approach to having first_use() called only
once, like a helper class, but this is a more concise approach.
--
Richard Herring