5

This a question related to the initialization of objects in C++.

I have a group of classes (not instances), inheriting from a common base class, and I need them to register info about themselves in a container (specifically a map) when the program starts.

The problem is that I need it to be dynamic. The container is defined in an independent project, different from the classes. I would prefer to avoid making multiple hard-coded versions of the library, one for each set of classes in each program that uses it.

I thought about having a static instance of a special class in each of these subclasses, that would make the registration in its constructor. However, I have found no way to guarantee that the container will be constructed before the construction of these objects.

I should also note that the information in the container about the subclasses should be available before any instance of these subclasses is created.

Is there a way to do this, or imitate a static constructor in C++ in general?

1
  • can't you make the registry object (your map) a singleton that is dynamically created via getInstance()?
    – Kevin
    Mar 15, 2011 at 18:51

6 Answers 6

2

You are describing different problems all at once. On the particular issue of having some sort of static initialization, a simple approach is creating a fake class that will perform the registration. Then each one of the different classes could have a static const X member, the member will have to be defined in a translation unit, and the definition will trigger the instantiation of the instance and the registration of the class.

This does not tackle the hard problem, which is the initailization order fiasco. The language does not provide any guarantee on the order of initialization of objects in different translation units. That is, if you compile three translation units with such classes, there is no guarantee on the relative order of execution of the fake member. That is also applied to the library: there is no guarantee that the container in which you want to register your classes has been initialized, if such container is a global/static member attribute.

If you have access to the code, you can modify the container code to use static local variables, and that will be a step forward as to ensure the order of initialization. As a sketch of a possible solution:

// registry lib
class registry { // basically a singleton
public:
   static registry& instance() { // ensures initialization in the first call
      static registry inst;
       return inst;
   }
// rest of the code
private:
   registry(); // disable other code from constructing elements of this type
};
// register.h
struct register {
   template <typename T>
   register( std::string name ) {
       registry::instance().register( name, T (*factory)() ); // or whatever you need to register
   }
};
// a.h
class a {
public:
   static a* factory();
private:
   static const register r;
};
// a.cpp
const register a::r( "class a", a::factory );
// b.h/b.cpp similar to a.h/a.cpp

Now in this case there is no definite order among the registration of the a and b classes, but that might not be an issue. On the other hand, by using a local static variable in the registry::instance function the initialization of the singleton is guaranteed to be performed before any call to the registry::register methods (as part of the first call to the instance method).

If you cannot make that change you are basically out of luck and you cannot guarantee that the registry will be instantiated before the other static member attributes (or globals) in other translation units. If that is the case, then you will have to postpone the registration of the class to the first instantiation, and add code to the constructor of each class to be registered that ensures that the class is registered before actual construction of the object.

This might or not be a solution, depending on whether other code creates objects of the type or not. In the particular case of factory functions (first one that came to mind), if nothing else is allowed to create objects of types a or b... then piggy backing registration on constructor calls will not be a solution either.

2
  • Thank you. That looks like what I am looking for. As for that last thing, are you referring to the possibility that the compiler may omit compiling a class, if it's not constructed somewhere?
    – Chris
    Mar 15, 2011 at 19:25
  • Not really, but rather to the fact that without having information on what your code does, it is hard to tell whether you are actually instantiating objects of those types somewhere else. If your code does not create objects of a then adding the registration call to the a constructor will not have any effect --no constructor called => no registration performed Mar 15, 2011 at 20:13
0

This is a candidate for the Singleton pattern. Basically, you want the container to be instantiated when the first instance of a subclass is instantiated. This can be facilitated by checking if the singleton pointer is NULL in the base-class constructor, and if so, then instantiate the container.

0

One idea is to pass a registration functor to the classes. Each descendant would execute the function to register. This functor could be passed in the constructor.

Example:

struct Registration_Interface
{
  virtual void operator() (const std::string& component_name) = 0;
};

struct Base
{
};

struct Child1
  : public Base
{
  Child(Registration_Interface& registration_ftor)
  {
     //...
     registration_ftor("Child1");
  }
};
0

See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14

One option is to construct the container lazily, when the first thing is added to it:

  void AddToContainer(...) {
    // Will be initialized the first time this function is called.
    static Container* c = new Container();
    c->Add(...);
  }

The only way to "imitate" a static constructor is to explicitly call a function to perform your static initialization. There is no other way to run code pre-main just by linking in a module.

0

You might use an "initialise on first use" pattern, and then instantiate a dummy static instance to ensure initialisation as early as possible.

class cExample
{
    public :
       cExample() ;

       // Static functions here

    private :
        static bool static_init ;

        // other static members here
}

cExample::static init = false ;

cExample::cExample()
{
    // Static initialisation on first use
    if( !static_init )
    {
        // initialise static members
    }

    // Instance initialisation here (if needed)
}

// Dummy instance to force initialisation before main() (if necessary)
static cExample force_init ;
0

It is against OOP paradigm, but how about having your static members form a linked list guided by 2 global variables? You could do something like that:

ClassRegistrator *head = nullptr;
ClassRegistrator *tail = nullptr;

struct ClassRegistrator {
    // ... Data that you need
    ClassRegistrator *next;
    ClassRegistrator(classData ...) {
      if (!head) 
          head = tail = this;
      else {
        tail->next = this;
        tail = this;
      }
      // ... Do other stuff that you need for registration
    }
};

// The class you want to register
class MyClass { 
    static ClassRegistrator registrator;
}

ClassRegistrator MyClass::registrator(...); // Call the constructor

I believe the global variables, as they don't need have a constructor, but are just pure data, are guaranteed to be already initialised when you begin the execution of your code.

Obviously this is not thread-safe, etc, but should make your job done.

1
  • C++ is multiparadigm, why would it matter if something is not OOP? The whole point is being able to program how you want. Nov 21, 2022 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.