Call method only if pointer is not nullptr

Viewed 2866

I have an interface class and a pointer that may be nullptr and if it is I just skip the method call:

if (ptr != nullptr)
{
    ptr->SomeMethod();
}

...

if (ptr != nullptr)
{
    ptr->SomeOtherMethod();
}

...

if (ptr != nullptr)
{
    ptr->SomeMethodThatWasntMentionedBefore();
}

UPDATE: The below isn't quite correct:

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)?

Is there any better way?

3 Answers
Related