Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why might a static data member not get initialized?

I'm trying to register a bunch of classes with a factory at load time. My strategy is to harness static initialization to make sure that before main() begins, the factory is ready to go. This strategy seems to work when I link my library dynamically, but not when I link statically; when I link statically, only some of my static data members get initialized.

Let's say my factory builds Cars. I have CarCreator classes that can instantiate a handful of cars, but not all. I want the factory to collect all of these CarCreator classes so that code looking for a new Car can go to the factory without having to know who will be doing the actual construction.

So I've got

CarTypes.hpp

enum CarTypes
{
   prius = 0,
   miata,
   hooptie,
   n_car_types
};

MyFactory.hpp

class CarCreator
{
public:
   virtual Car * create_a_car( CarType ) = 0;
   virtual std::list< CarTypes > list_cars_I_create() = 0;
};

class MyFactory // makes cars
{
public:
   Car * create_car( CarType type );
   void factory_register( CarCreator * )

   static MyFactory * get_instance(); // singleton
private:
   MyFactory();

   std::vector< CarCreator * > car_creator_map;
};

MyFactory.cpp

MyFactory:: MyFactory() : car_creator_map( n_car_types );

MyFactory * MyFactory::get_instance() {
   static MyFactory * instance( 0 ); /// Safe singleton
   if ( instance == 0 ) {
      instance = new MyFactory;
   }
   return instance;
}

void MyFactory::factory_register( CarCreator * creator )
{
   std::list< CarTypes > types = creator->list_cars_I_create();
   for ( std::list< CarTypes >::const_iteator iter = types.begin();
         iter != types.end(); ++iter ) {
      car_creator_map[ *iter ] = creator;
   }
}

Car * MyFactory::create_car( CarType type ) 
{
   if ( car_creator_map[ type ] == 0 ) { // SERIOUS ERROR!
      exit();
   }
   return car_creator_map[ type ]->create_a_car( type );
}

...

Then I'll have specific cars and specific car creators:

Miata.cpp

class Miata : public Car {...};

class MiataCreator : public CarCreator {
public:
   virtual Car * create_a_car( CarType );
   virtual std::list< CarTypes > list_cars_I_create();
private:
   static bool register_with_factory();
   static bool registered;
};

bool MiataCreator::register_with_factory()
{
   MyFactory::get_instance()->factory_register( new MiataCreator );
   return true;
}

bool MiataCreator::registered( MiataCreator::register_with_factory() );

...

To reiterate: dynamically linking my libraries, MiataCreator::registered will get initialized, statically linking my libraries, it will not get initialized.

With a static build, when someone goes to the factory to request a Miata, the miata element of the car_creator_map will point to NULL and the program will exit.

Is there anything special with private static integral data members that their initialization will be somehow skipped? Are static data members only initialized if the class is used? My CarCreator classes are not declared in any header file; they live entirely within the .cpp file. Is it possible that the compiler is inlining the initialization function and somehow avoiding the call to MyFactory::factory_register?

Is there a better solution to this registration problem?

It is not an option to list iall of the CarCreators in a single function, register each one explicitly with the factory, and then to guarantee that the function is called. In particular, I want to link several libraries together and define CarCreators in these separate libraries, but still use a singular factory to construct them.

...

Here are some responses I am anticipating but which do not address my problem:

1) your singleton Factory isn't thread safe. a) Shouldn't matter, I'm working with only a single thread.

2) your singleton Factory may be uninitialized when your CarCreators are being initialized (i.e. you've got a static initialization fiasco) a) I'm using a safe version of the singleton class by putting the singleton instance into a function. If this were a problem, I should see output if I added a print statement to the MiataCreator's::register_with_factory method: I don't.

like image 425
Andrew Avatar asked Aug 19 '09 15:08

Andrew


People also ask

Why don't we initialize the static data member in the constructor of the class?

A static data member is shared among all instances of the class. It can be initialized once (by definition of initialization), so it wouldn't make sense to initialize it for each instance. You could, however, assign it a value (or mutate the existing value) in the constructor body.

How do you initialize a static data member?

Static Data Member Initialization in C++ We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator, then the variable name. Now we can assign some value.

Why are static variables initialized to zero?

Yes, it's because it's in the standard; but really, it's because it's free. Static variables look just like global variables to the generated object code.

Can we initialize static data member in constructor?

If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.


3 Answers

I think you have a static initialization order fiasco, but not with the Factory.

It's not that it's the registered flag is not getting initialized, it's just not getting initialized soon enough.

You cannot rely on static initialization order except to the extent that:

  1. Static variables defined in the same translation unit (.cpp file) will be initialized in the order listed
  2. Static variables defined in a translation unit will be initialized before any function or method in that translation unit is invoked for the first time.

What you cannot rely on is that a static variable will be initialized before a function or method in some other translation unit is invoked for the first time.

In particular, you cannot rely on MiataCreator::registered (defined in Miata.cpp) to be initialized before MyFactory::create_car (defined in MyFactory.cpp) is invoked for the first time.

Like all undefined behavior, sometimes you will get what you want, and sometimes you won't, and the strangest most seemingly-unrelated things (such as static versus dynamic linking) can change whether it works the way you want it to or not.

What you need to do is create static accessor method for the registered flag that is defined in Miata.cpp, and have the MyFactory factory get the value through this accessor. Since the accessor is in the same translation unit as the variable definition, the variable will be initialized by the time the accessor runs. You then need to call this accessor from somewhere.

like image 172
Tyler McHenry Avatar answered Oct 25 '22 03:10

Tyler McHenry


If with static linking you mean adding all object files(.o) to the binary, that should work like the dynamic stuff, if you made a (.a) static library the linker will not link them inside as only the used objects inside the static library are linked and in this case none is used explicitly.

All the auto-registering techinques depend on load-time code and its ways to avoid the static fiasco, like the function that creates the object and returns it on demand.

But if you don't manage to load that ever it won't work, linking object files together works, and loading dynamic libraries as well, but static libraries will never link without explicit dependencies.

like image 41
Arkaitz Jimenez Avatar answered Oct 25 '22 04:10

Arkaitz Jimenez


Generally with static libaries, the linker will only pull out the .o files from that library which the main program references. Since you're not referencing MiataCreator::registered or really anything in Miata.cpp but rely on static initiailization the linker won't even include that code in your exe if it's linked from a static library-

Check the resulting executable with nm or objdump(or dumpbin if you are on windows) whether the code for MiataCreator::registered is actually included in the exe file when you link statically.

I don't know how to force the linker to include every bits and pieces of a static library though..

like image 23
nos Avatar answered Oct 25 '22 04:10

nos