Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deferring C++ static object construction - GCC on Linux

Tags:

c++

gcc

Imagine I have a C++ class called MyClass.

Imagine that I have no access to the source code of MyClass ... it is contained in a library and I am supplied only the library and the header file for MyClass.

Imagine that the class itself requires environment pre-configuration ... for example ... before the constructor of the class can be called, I need to do some setup. The class is normally meant to be used as follows:

void func() {
   doGlobalSetup();
   MyClass myInstance(1,2,3);
   myInstance.doSomething();
   ...
}

Now I have the situation where we need to create a global instance of the class such as:

MyClass myInstance(1,2,3);

int main(int argc, char *argv[]) {
   doGlobalSetup();
   myInstance.doSomething();
}

The problem is that in this story, the instance of MyClass is created before the call to doGlobalSetup(). It is instantiated before main() is called. What I want to do is either defer the creation of myInstance() till later or be able to run doGlobalSetup() somehow before the instantiation of the class.

This is a simplification of the actual story ... so let us assume:

  1. I can't change the internals of MyClass.
  2. There must be an instance variable called myInstance of type MyClass (I can't change the logic to MyClass *pMyInstance).

Many thanks for reading.

like image 389
Kolban Avatar asked Dec 23 '15 15:12

Kolban


2 Answers

Since you've constrained the problem such that new cannot be used, you should be able to create the object as always and copy it to the global instance. For example:

MyClass createMyClass()
{
    doGlobalSetup();
    return MyClass(1, 2, 3);
}

MyClass myInstance = createMyClass();

int main()
{
    myInstance.doSomething();

    return 0;
}
like image 144
James Adkison Avatar answered Oct 06 '22 02:10

James Adkison


Does it suit your needs?

namespace
{
    int doStaticGlobalSetup()
    {
        doGlobalSetup();
        return 0;
    }
}
MyClass myInstance(doStaticGlobalSetup() + 1,2,3);

int main() {
   myInstance.doSomething();
   return 0;
}
like image 21
YSC Avatar answered Oct 06 '22 01:10

YSC