Sign in to follow this  
Yohumbus

avoiding construction ordering problems with static data

Recommended Posts

Yohumbus    152
Alright, what I want do do is make a pluggable object factory in C++, but I want to avoid the problems associated with using static data in classes. What I mean by this is I will have some sort of static map that other static classes will access automatically because they are static to register themselves. I have had stuctural problems before that have required redesigning my code to prevent static classes that are constructed from accessing other static data that had not been initialized. That time I did it by simply structuring my code to not use static data but with this design pattern I need things to be contructed at static construction time that access maps or other data structured that would be constructed then too. I know that the standard leaves the order of static data construction to be undefined but from the tests I did(with minGW) I found that primitive data(a character pointer in this case) is always what you specify it as. I figure this is the case because primitive data, lacking a constructor, takes no code to assign a value to but I am wondering how safe it would be to assume this. If it is always true (does the standard state this for state primitive data types?) then I know how I could make the map or other data structure be constructed if it hadn't already been. If it isn't safe to assume that though I would be interested in finding out about other design patterns that include all of the functionality of pluggable factories without the chance of random segfaults based on how my compiler decides to order the code. I don't want this do become a discussion (flamewar) over my choice of pattern because half the search results I found to resolve this issue (yes I did search first) degenerated into that.

Share this post


Link to post
Share on other sites
nmi    978
The standard says that POD types are initialized when the program is started.

So take this class:

class C
{
C(int i) { ... }
static int i;
};
int C::i = 3;


Here C::i will by placed into the data segment by the compiler. So the value is already stored in your executable.


class D
{
static C c;
};
C D::c(3);


Here D::c will be initialized before main starts, but there is no actual data in your data segment. The compiler generates a constructor call, but as you know it is not safe to rely on the order of constructor calls.

So for POD-types it will work, for class instances not.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this