Print
Category: C++ Programming
Hits: 835

Some times a template class must have a member variable of type <T>. Following questions are rising up: How do I initialise the member variable, if I don't know if it is a pointer, primitive datatype or even an other object?

Using the memset function will cause memory leaks, if the template is used for complex objects, creating member pointers in their constructors. The member pointer will be set to NULL.

Most C++ compilers has an undocumented function to initialize even primitive datatypes using their standard constructor T(). This feature is used in following example:


template <class TKeyType, class T> class TMap
 : public TZObject, public IMap<TKeyType, T>
{
  public:
    TMap() : m_tEmpty(T())
    {
      // DO NOT USE MEMSET. 
      // This causes memory leaks on complex objects
      //memset(&m_tEmpty, 0, sizeof(T));
    }
  
  private:
    ///Empty item
    T m_tEmpty;
};

If your compiler is not supporting this feature, there is an other way how to solve this problem. We are writing a static method returning a static local variable of the type <T>. The static variable will be initialized by the compiler with 0 (zero) for primitive datatypes.


template <class TKeyType, class T> class TMap
 : public TZObject, public IMap<TKeyType, T>
{
  public:
    TMap() : m_tEmpty(getDefaultEmpty())
    {
      // DO NOT USE MEMSET. 
      // This causes memory leaks on complex objects
      //memset(&m_tEmpty, 0, sizeof(T));
    }
  
  private:
    ///Empty item
    T m_tEmpty;

    static const T& getDefaultEmpty()
    {
        static const T Empty; // is initialized by compiler
        return Empty;
    }
};

Still this will fail if we want to store references.