1

I have a macro:

#define checkAlloc(ans)  checkPointer((ans), __FILE__, __LINE__); 

which is used to wrap around any pointer allocation to check it is valid (used for checking memory allocations on a GPU device side).

The macro is used as follows:

SomeObject* myObj = checkAlloc(new SomeObject());

and the checkPointer function is implemented as:

inline __device__ SomeObject* checkPointer(SomeObject* pointer, char *file, int line)
{
    if (pointer == nullptr)
    {
        // do error logging
    }
    return pointer;
}

Now, it is very inconvenient to create a new version of the function for each type of object I might allocate to. Templates are also not an option since I would like syntax to be clear - i.e. just putting checkAlloc(…) around each allocation rather than checkAlloc<SomeObject>(…) which is ugly and hopefully unnecessary.

Ideally I would like to change the checkPointer to be:

inline __device__ auto checkPointer(auto pointer, char *file, int line)

but I understand auto cannot be used for a function parameter yet. The GPU code supports C++14 so lambdas could be used as a potential workaround from I can read at https://stackoverflow.com/a/29945034/7283981 but I am not familiar enough with lambdas to know how to do this. Any ideas?

Cody Gray
  • 230,875
  • 49
  • 477
  • 553
  • 2
    Template functions have argument deduction capabilities. What exactly is "unclear"? You seem to have few misconceptions here. – StoryTeller - Unslander Monica Oct 17 '17 at 14:45
  • In fact, `checkAlloc(…)` *would* be unnecessary, as the pointer's type can be automatically deduced. – Cody Gray Oct 17 '17 at 14:46
  • A template should do exactly what you want here. You don't have to specify the type when you call a template unless it is not deducible. In this case it would be so you can just use it like you would a normal function. – NathanOliver Oct 17 '17 at 14:46
  • BTW, `new SomeObject()` would not return `nullptr` but throw in case of error. – Jarod42 Oct 17 '17 at 15:36
  • Thanks all. In my case new SomeObject() won't throw as it is in GPU land where exception handling doesn't exist. – john_smith_lon Oct 17 '17 at 16:56

1 Answers1

3

This is the perfect case for a template, I don't understand why you are trying to avoid it:

template < typename T >
inline __device__ T* checkPointer(T* pointer, const char *file, int line)
{
  if (pointer == nullptr)
  {
    // do error logging
  }

  return pointer;
}

This is very clear and clean and you can use it as if there was an auto there:

int main(int argc, char** argv)
{
    SomeObject* myObj = checkAlloc(new SomeObject());
}

As you can see, there are automatic argument deduction capabilities that don't even require any type specification...

Oh, and notice that I changed char * file to const char * file as C++11 doesn't allow conversion of literals to char *

Daniel Trugman
  • 6,930
  • 17
  • 39