NotNull
Rather than sprinkle your functions with precondition asserts that arguments aren't null, use the following, self-documenting type as part of the function's signature:
#include <assert.h> #include <stdio.h> template<typename T> class NotNull { public: NotNull(T object) : _object(object) { assert(object); } operator T() const { return _object; } private: T _object; }; void printNumber(NotNull<int*> arg) { printf("%d\n", *arg); } int main() { int i = 10; printNumber(&i); // fine int* p = 0; printNumber(p); // asserts }
Always a fallback, or as a compliment to the above: [HTML_REMOVED] void printNumber(int* arg) { assert(arg && "Null pointer referenced in 'printNumber(int* arg)' !"); printf("%d\n", *arg); } [HTML_REMOVED] The above assert would behave just as it would in a normal assert() call, since strings evaluate to non-zero. Then, if the assert is encountered, the msgbox or line in stderr or wherever is pretty descriptive. It might even be a good idea to make use of the LINE and FILE macros. But the above message is sufficient enough, IMO.
hmm.. it may help...
what if T is not a pointer? you could provide the template specialization only for *T (for non-pointer-types T the compiler will fail to have a definition)
shouldn't you use a reference 'T &object' in your constructor?
but I think this is a nice idea - will test it, thank you!
my suggestion:
ifdef NDEBUG
define NotNull(X) X
else // in Debug-Mode
template class NotNull;
// template specialization only for pointer-types template class NotNull { public: NotNull(T* object) : _object(object) { assert(object); }
private: T *_object; };
define NotNull(X) NotNull
endif // in Debug-Mode
g, all template specifications got lost in the comment^^
another try:
ifdef NDEBUG
define NotNull(X) X
else // in Debug-Mode
template class NotNull;
template // template specialization only for pointer-types class NotNull { public: NotNull(T* object) : _object(object) { assert(object); }
private: T *_object; };
define NotNull(X) NotNull
endif // in Debug-Mode
narf, see here:
http://stackoverflow.com/questions/1180832/avoiding-null-pointer-exceptions-in-a-large-c-code-base/1764061#1764061
(one link)