Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Macro for null safe pointer access

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!

like image 568
RoboCop87 Avatar asked Aug 22 '26 14:08

RoboCop87


2 Answers

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.

like image 94
Lundin Avatar answered Aug 25 '26 04:08

Lundin


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.

like image 45
John Zwinck Avatar answered Aug 25 '26 02:08

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!