[英]Throwing a NullPointerException in C++
Is it possible to let C++ throw a NPE when calling a method on a nullptr object, instead of going in undefined behaviour?在 nullptr 对象上调用方法时,是否可以让 C++ 抛出 NPE,而不是进入未定义的行为? I could create a handler for a SEGFAULT signal but this would be realy dangerous, because not every SEGFAULT is a NullPointerException.
我可以为 SEGFAULT 信号创建一个处理程序,但这会非常危险,因为并非每个 SEGFAULT 都是 NullPointerException。 If i have to do it via just checking in an if clause, is there a efficiant way to do so?
如果我必须通过检查 if 子句来做到这一点,有没有一种有效的方法来做到这一点? Maybe also on compiletime?
也许也在编译时?
Yes you can but its not really a good idea (you should not be handling pointers anyway, in modern C++ pointers are held inside objects that manage their lifespan).是的,您可以,但这不是一个好主意(无论如何您都不应该处理指针,在现代 C++ 中,指针保存在管理其生命周期的对象中)。
You can always define a class that holds the pointer.您始终可以定义一个包含指针的类。 Then when you try and use
operator->()
it will throw if the held pointer is nullptr
.然后,当您尝试使用
operator->()
,如果持有的指针为nullptr
,它将抛出。
template<typename T>
class ThrowingUniquePtr
{
T* ptr;
public:
// STUFF to create and hold pointer.
T* operator->()
{
if (ptr) {
return ptr;
}
throw NullPointerException; // You have defined this somewhere else.
}
};
class Run
{
public:
void run() {std::cout << "Running\n";}
};
int main()
{
ThrowingUniquePtr<Run> x(new Run);
x->run(); // will call run.
ThrowingUniquePtr<Run> y(nullptr);
y->run(); // will throw.
}
Another way of exception handling: calling a function using NULL pointer异常处理的另一种方式:使用NULL指针调用函数
#include <iostream>
#include <typeinfo>
using namespace std;
char str_NullPointer[25] = "NULL Pointer exception";
char str_Arithmetic[25] = "Arithmetic exception";
class A
{
public:
int i = 20;
public:
int function()
{
printf("Function start\n");
try
{
if (this)
{
printf("value of i = %d \n", i);
}
else
{
throw str_NullPointer; /* Exception thrown in Case 2 */
}
}
catch(const int s)
{
printf("%d\n", s);
}
catch(const char* s)
{
printf("%s in %s\n", s, typeid(this).name()); /* Exception and Class Name */
}
printf("Function end\n\n\n");
}
};
int main() {
//code
printf("Case 1: With Pointer\n");
A *obj = new A();
obj->i = 20;
obj->function();
printf("Case 2: With NULL Pointer\n");
delete obj;
obj = NULL;
obj->function();
return 0;
}
Output:输出:
Case 1: With Pointer
Function start
value of i = 20
Function end
Case 2: With NULL Pointer
Function start
NULL Pointer exception in P4abcd
Function end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.