Optional parameter for pointer reference?

How to declare the second parameter as optional?

template <typename T>
inline void Delete (T *&MemoryToFree,
    T *&MemoryToFree2 = ){
    delete MemoryToFree;
    MemoryToFree = NULL;

    delete MemoryToFree2;
    MemoryToFree2 = NULL;

}

I tried several things after the = operator, for example NULL, (T *) NULL, etc. Can this be done?

The only way the compiler allowed me to do this is to use overloading ...

    template <typename T, typename T2>
inline void Delete (T *&MemoryToFree, T2 *&MemoryToFree2){
    delete MemoryToFree;
    MemoryToFree = NULL;

    delete MemoryToFree2;
    MemoryToFree2 = NULL;
}
+3
source share
4 answers

You can just overload the function

template <typename T>
inline void Delete (T *&MemoryToFree){
        delete MemoryToFree;
        MemoryToFree = NULL;
}

template <typename T, typename T2>
inline void Delete (T *&MemoryToFree, T2 *&MemoryToFree2){
        delete MemoryToFree;
        MemoryToFree = NULL;

        delete MemoryToFree2;
        MemoryToFree2 = NULL;
}
+12
source

You can always write a simple “static l-value generator on demand” and use it as the default value for your parameter

template <typename T> inline T& get_lvalue() {
  static T t;
  return t;
}

In your code

template <typename T> 
inline void Delete(T *&MemoryToFree, T *&MemoryToFree2 = get_lvalue<T*>())
+8
source

, . .

+2

, gcc 4.3.2.

void fn( int*const & i = 0 )
{
    delete i;
}

so maybe you can adapt it. To resolve the default argument you will need *const. Default permissions are allowed for const-references.

Edit

I just realized that its marking is *constuseless for you, since you want to remove the pointer in the same way as it does delete.

0
source

Source: https://habr.com/ru/post/1720308/


All Articles