I want to write a C/C++ macro for null safe pointer access. I currently have this, which works well:
#define NULL_SAFE(p, e) if (p) p->e
NULL_SAFE(myPtr, myMethod(myArg));
But what I really want is to have something like this:
NULL_SAFE(
myPtr, myMethod(myArg),
myOtherPtr, myOtherMethod(myOtherArg),
yetAnotherMyPtr, plsStopMethod(grArg),
...
);
which would expand to:
if (myPtr) myPtr->myMethod(myArg);
if (myOtherPtr) myOtherPtr->myOtherMethod(myOtherArg);
if (yetAnotherMyPtr) yetAnotherMyPtr->plsStopMethod(grArg);
I can think of a whole bunch of these I might like to use, but they all operate on the same concept as this.
Is this possible? Does this already exist somewhere? Any suggestions? Thanks for your help!
If the NULL check is part of an algorithm, then just type out the NULL check explicitly without any icky macros.
If the NULL check is a way of defensive programming, the correct way to do this is assert(ptr);. If the assert ever triggers, go fix the bug that caused it. Repeat until there are no bugs left, then remove the assert from the production-quality code.
C++11:
inline void null_safe()
{
}
template <typename Ptr, typename Fn, typename... Args>
void null_safe(Ptr&& ptr, Fn&& fn, Args&&... args)
{
if (ptr)
fn();
// you could put "else" here
null_safe(std::forward<Args>(args)...);
}
You can use any callable as the second argument, so:
int f2() {
return printf("f2\n");
}
int f3() {
return printf("f3\n");
}
int main()
{
int i1 = 1;
null_safe(
&i1, f2
);
null_safe(
NULL, f2,
&i1, f3
);
}
You can also use any predicate as the first argument.
Why it's NULL there and not nullptr is left as an exercise for the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With