用于空安全指针访问的C/C++宏

Rob*_*p87 3 c c++ macros null pointers

我想为空安全指针访问编写一个C/C++宏.我目前有这个,效果很好:

#define NULL_SAFE(p, e) if (p) p->e
NULL_SAFE(myPtr, myMethod(myArg));
Run Code Online (Sandbox Code Playgroud)

但我真正想要的是拥有这样的东西:

NULL_SAFE(
  myPtr, myMethod(myArg),
  myOtherPtr, myOtherMethod(myOtherArg),
  yetAnotherMyPtr, plsStopMethod(grArg),
  ...
);
Run Code Online (Sandbox Code Playgroud)

这将扩展到:

  if (myPtr) myPtr->myMethod(myArg);
  if (myOtherPtr) myOtherPtr->myOtherMethod(myOtherArg);
  if (yetAnotherMyPtr) yetAnotherMyPtr->plsStopMethod(grArg);
Run Code Online (Sandbox Code Playgroud)

我可以想到我可能想要使用的一大堆这些,但它们都运行在与此相同的概念上.

这可能吗?这已经存在于某个地方吗?有什么建议?谢谢你的帮助!

Lun*_*din 5

如果NULL检查是算法的一部分,那么只需显式地键入NULL检查,而不需要任何icky宏.

如果NULL检查是一种防御性编程方式,那么正确的方法就是这样做assert(ptr);.如果断言触发,请修复导致它的错误.重复,直到没有错误,然后从生产质量代码中删除断言.