c++ - 仅当指针不是 nullptr 时调用方法

标签 c++ c++11

我有一个接口(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/

相关文章:

Python ctype 直接调用具有原始偏移量的函数

c++ - std::vector::reserve( unknown m ),我知道 m<<N (通常)并且知道 N

c++ - Visual C++ 为什么 std::move 崩溃

c++ - 新标准的特性对 C++11 中的 boost 库实现有重大影响吗?

c++ - 转换 c_str() 仅适用于短字符串

c++ - 如何在msvc中添加高亮关键字

c++ - 如何获取在对 VirtualAlloc 的初始分配调用中保留的区域大小

c++ - 关于 RCF 中间件二进制大小

c++ - 使用智能指针在窗口消息中将对象作为 WPARAM 传递

C++ 程序不会因为 memcpy 而终止