Archived

This topic is now archived and is closed to further replies.

aleks_1661

C++ : Order of evaluation of runtime objects

Recommended Posts

For my latest project I have been writing a class factory based class heirarchy where each class is automatically registered at runtime. This is achieved by using a CClassReg class which is created by a macro:

#define IMPLEMENT_CLASS( c )	\
static BaseClass* CreateClass_##c##()	\
{					\
	c* newClass = new c;		\
	return newClass;		\
}					\
CClassReg g_##c##_reg( #c, CreateClass_##c## );	

 
This creats the CClassReg class which is instantiated when the program is executed. This registers with the ClassFactory and gets added to a static vector list. The problem I am having is I am not completely sure about the order in which such global objects are created. The problem I have is that depending on where the class is defined in the program, sometimes the classes are registered before the ClassFactory is constructed, when it is constructed the list is reset, loosing all the previous classes. Anyone know the order that objects are created at runtime? Thanks Alex. "There are 10 types of people, those who know binary and those who dont!"

Share this post


Link to post
Share on other sites
(simple answer): you can''t know

However, if you have a function with a static variable it will be created the first time you call the function:


int& getGlobalInteger() {
static int someValue = 0;
return someValue;
}


So if you access your globals using functions instead of by name then you can be sure that they''ll be created when you want to use them.

So if you access the registry using a function rather than by name it will have definitely been created.

Share this post


Link to post
Share on other sites
Cheers mate, nice elegant solution.

So if I make the factory a proper singleton and cause it to return the classfactory object using a function it will always be created before the registration.

Cheers!

Alex

Share this post


Link to post
Share on other sites