Complex Static Initializations

C

cppaddict

I would like to know the best way to initialize complex static member
variables. In addition, I want to avoid creating an Init() method
that is called by the ctor, since there's no need to wait for that
call in my application. My current attempt is OK, but it creates an
extra member variable that is extraneous:

<code>
class A {
private:
static std::vector<int> _v;
static bool init();
static bool isInit;
public:
A() : _a(1) {}
};

// This would go in the implementation file

std::vector<int> A::_v;
bool A::init() {
_v.push_back(1);
_v.push_back(2);
return true;
}
bool A::isInit = A::init();
</code>

Is there a better way to do this?

thanks for any thoughts,
cpp
 
D

Dave Townsend

I'm not following your posting, but I would suggest you consider the
singleton pattern. Basically, this constructs a single static object and
provides a pointer to it. You can also control the construction so that if
you never access the object, it is never created. You can put just about
any initialization into the static object you wish.

Here's an example you can use....

#include <vector>
using namespace std;

class Singleton {
private:
static Singleton* _data;

std::vector<int> _v;
public:
Singleton()
{
_v.push_back(1);
_v.push_back(2);
}
int get_first()
{
return _v[0];
}
int get_second()
{
return _v[1];
}
static Singleton* getData()
{
if (_data ==0)
{
static Singleton s;
_data = &s;

}
return _data;

}


};
Singleton* Singleton::_data = 0;



int main(int argc, char* argv[])
{

Singleton* s = Singleton::getData();
int second = s->get_first();
int first = s->get_second();
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top