起因
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;
}