QT/C++检查指针是否为空

起因

    QT/C++程序使用需要判定指针是否为空以保证程序可以正常运行不崩溃。

使用

    一般实现有两种情况:
    1. 使用宏
    2. 使用模板
    从了解情况来看,如果性能要求较高使用宏,如果性能要求不高且方便调试的话使用模板,两种都有各自的优势,视情况而定。

####################################################使用宏判断指针是否为空
#include <iostream>
#include <system_error>

// 宏定义
#define CHECKPOINTER(ptr) \
do \
{ \
    if (nullptr == (ptr)) \
    { \
        throw std::system_error(errno, std::system_category(), "ptr is null"); \
    } \
} while (0)

int main() 
{
    int* p = nullptr;

    try 
    {
        CHECKPOINTER(p);
    } 
    catch (const std::system_error& e) 
    {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}

####################################################使用模板判断指针是否为空
#include <iostream>
#include <system_error>

// 函数模板用于检查指针是否为空
template <typename T>
void CheckPointer(const T* ptr) 
{
    if (nullptr == ptr) 
    {
        throw std::system_error(errno, std::system_category(), "ptr is null");
    }
}

int main() {
    int* p = nullptr;

    try 
    {
        CheckPointer(p);
    }
    catch (const std::system_error& e) 
    {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值