This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

My singleton template does'nt work



Hi,

This singleton code doesn't work :

////////////////////////////////////////////////////       code                  /////////////:

#ifndef __SINGLETON
#define __SINGLETON

#include <stddef.h>

template<typename T>
class Singleton
{
protected:
    Singleton()   {}
    ~Singleton() { _singleton = NULL;}

public:
    static T inline *getInstance()
    {
          if ((static_cast<T*>(NULL)) == _singleton) {  _singleton = new T; }
          return (static_cast<T*>(_singleton));
    }

    static void kill()
    {
         if (NULL != _singleton)
         {
              delete _singleton;
              _singleton = NULL;
        }
    }

private:
    static T *_singleton;
};

template<typename T>
T *Singleton<T>::_singleton = (static_cast<T*>(NULL));

#endif

/////////////////////////// end of code //////////////////////////////////////////////

In  my case, "_singleton" variable  is always null, even after instantiation.

Is this a compiler/linker problem?

Must I use special options   ?

Note : Templates without static variables are working on the same environment.

Thanks by advance.

Gilles Peltier

  • Hi Gilles,

    I don't see an obvious problem. Maybe try placing a breakpoint at the entry to the *getInstance() function, and then single-stepping to confirm that the if statement is taken and the result of the constructor call is a non-null instance?

    If you think this may be a compiler problem, maybe try posting on the compiler forum here:

    http://e2e.ti.com/support/development_tools/compiler/default.aspx

     

  • I had a look at the compiler forum.

    I found this thread:

    http://e2e.ti.com/support/development_tools/compiler/f/343/t/160822.aspx

    and one response from  Ti was:

    Note that there are expected deviations from the C++ standard in COFF ABI mode, particularly with respect to static locals in template member functions, but this problem is resolved in EABI (this issue is due to a fundamental limitation of COFF ABI).  This code should work just fine in EABI mode, regardless of whether inlining occurs."

    I will try EABI mode later  ; I never used it before.

    May I will find other problems !

    Thanks