我有一个接口(interface)类和一个可能是 nullptr
的指针,如果是,我就跳过方法调用:
if (ptr != nullptr)
{
ptr->SomeMethod();
}
...
if (ptr != nullptr)
{
ptr->SomeOtherMethod();
}
...
if (ptr != nullptr)
{
ptr->SomeMethodThatWasntMentionedBefore();
}
更新: 以下不太正确:
I can improve this code readability with the following macro:
#define CALL_IF_NOT_NULLPTR(ptr, method_call) if (ptr != nullptr) { ptr->method_call; }; CALL_IF_NOT_NULLPTR(ptr, SomeMethod()); CALL_IF_NOT_NULLPTR(ptr, SomeOtherMethod()); CALL_IF_NOT_NULLPTR(ptr, SomeMethodThatWasntMentionedBefore());
Is there any way to do the same without macros (
C++11
solutions are preferred)?
有没有更好的办法?
最佳答案
不要与语言作对:
if (ptr) ptr->SomeMethod();
非常清晰、可读,并且比难以调试的宏替代方案或花哨的包装类具有更少的字符。它还明确说明了 ptr
可能 被计算两次的事实。
C++(还)没有“仅当非空运算符时才调用”cf。 C#
关于c++ - 仅当指针不是 nullptr 时调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45412987/