detecting constructor called before main

4

440gtx

I have a class that maintains a static std::list of its instances.
Thus, due to the order of constructors ambiguity of itself and
std::list, it cannot be safely instantiated until after main is
called. What I would like to do is put in an assert if it is
instantiated too early, but unsure how to detect this case. Or perhaps
there is a better design for instance tracking?
 
R

robertwessel2

I have a class that maintains a static std::list of its instances.
Thus, due to the order of constructors ambiguity of itself and
std::list, it cannot be safely instantiated until after main is
called. What I would like to do is put in an assert if it is
instantiated too early, but unsure how to detect this case. Or perhaps
there is a better design for instance tracking?


Set a global flag (that's initialized not-set) at the top of main().
Test it in the ctor in question. Note that this will run *after* any
ctors or initializers called for automatics as main is entered.
 
A

Alan Johnson

I have a class that maintains a static std::list of its instances.
Thus, due to the order of constructors ambiguity of itself and
std::list, it cannot be safely instantiated until after main is
called. What I would like to do is put in an assert if it is
instantiated too early, but unsure how to detect this case. Or perhaps
there is a better design for instance tracking?

Instead of declaring the list as a static member of the class, declare
it as a local static variable in a static function, like so:

class A
{
static std::list<A *> & get_list() ;

A()
{
get_list().push_back(this) ;
}
} ;

std::list<A *> & A::get_list()
{
static std::list<A *> instances ;
return instances ;
}

You are guaranteed that 'instances' will be constructed the first time
control passes over it, which should eliminate your problem.
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top