__gc class variable initializers not run. VS 2003 bug?

B

Bern McCarty

If I have a class that implements the singleton pattern like so:

public __gc class AppManager {
private:
AppManager(); // private constructor
public:
virtual ~AppManager();
static AppManager* i = new AppManager(); // this initializer won't ever
run unless the class is referenced from an initializer for global data
..
..
..

....then I get a System::NullReferenceException the first time that I try to
access the singleton instance through AppManager::i. However, if I add a
reference to the AppManager class from an initializer for global data, then
the class variable initializer is run and everything works just fine. For
example if I simply add:

static gcroot<AppManager*> *ensureInitializers4ClassVariablesAreRun = new
gcroot<AppManager*>(AppManager::i);

....then I'm good to go. I can step through _CRT_INIT and see all the right
initialization happen.

Shouldn't my class variables for my __gc class be guaranteed to be
initialized by the time that I make my first reference to the class no
matter how/where that reference is made from?

Bern McCarty
Bentley Systems, Inc.
 
E

Edward Diener

Bern said:
If I have a class that implements the singleton pattern like so:

public __gc class AppManager {
private:
AppManager(); // private constructor
public:
virtual ~AppManager();
static AppManager* i = new AppManager(); // this initializer
won't ever run unless the class is referenced from an initializer for
global data .

This isn't valid native C++ so I don't know if it is valid Managed C++. Is
it explained in the Managed C++ Extensions that this is valid ? How about
trying:

AppManager * AppManager::i = new AppManager();

public __gc class AppManager {
private:
AppManager(); // private constructor
public:
virtual ~AppManager();
static AppManager* i; }

In other words, initialize out of class, which is what unmanaged C++ has to
do. Does that work correctly ?
 

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

Top