Archived

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

En Dum En

Order of construction

Recommended Posts

Is there any way to determine the order in which static members of classes are constructed? I have two classes in different files, each having static members. I need one of the classes'' static members to be initialized before the ones in the other file. Unfortunatley, exactly the opposite happens.

Share this post


Link to post
Share on other sites
An example to clarify better what I am trying to achieve:


//File1.h / File1.cpp
class File2;
class File1
{
public:
static Register(File2* file) {list.push_back(file)}

static list< File2* > list;
};

list< File2* > File1::list;






//File2.h / File2.cpp
#include "file1.h"

class File2
{
public:
File2() { File1::Register(this)}

static File2 file2;
};

File2 File2::file2;



[edited by - en dum en on May 5, 2003 11:02:44 AM]

[edited by - en dum en on May 5, 2003 11:04:55 AM]

[edited by - en dum en on May 5, 2003 11:05:23 AM]

Share this post


Link to post
Share on other sites
Yes, but only in VC++, and it isn''t recommended:
Put the one that must be constructed first in a seperate .cpp file, and precede it with:

#pragma init_seg(lib)

Note that this isn''t generally a good idea, as the library initialisation segment is for 3rd party libraries only. This will also create a warning C4073, so you may want to precede it again with:
#pragma warning(disable:4073)

Share this post


Link to post
Share on other sites
This will get you a static memory leak (no matter, the OS will clean it up for us after the process has exited) but it works fine:

  
class File1
{
private:
static list<File2*>& GetFile2List();
public:
static Register(File2* file) { GetFile2List().push_back(file) }
};

list<File2*>& File1::GetFile2List()
{
static list<File2*>* pList = new list<File2*>;
return *pList;
}

class File2
{
public:
File2() { File1::Register(this)}
static File2 file2;
};
File2 File2::file2;




Update GameDev.net system time campaign - success at last

[edited by - dalleboy on May 5, 2003 12:12:36 PM]

Share this post


Link to post
Share on other sites
another compiler specific hack approach. In gcc the lib that is listed last in list sent to the linker will be linked first, so you can create a lib with only one static objet in it and link it last and it would be constructed first. I have used this hack :-(

Share this post


Link to post
Share on other sites
quote:

Is there any way to determine the order in which static members of classes are constructed?


There is no language support for this (vital) feature. I consider that as a major design flaw of C++.

Share this post


Link to post
Share on other sites