EOG*_*EOG -1 c++ exception-handling exception this
有一种简单的方法可以在c ++中抛出自定义空指针异常吗?我的想法是重新定义this指针,但它有3个问题:
thisthrows标准Acces Violation ExceptionVisual Studio将此显示为InteliSense错误(可编译)(不知道其他编译器做了什么)
#include <iostream>
#define this (this != nullptr ? (*this) : throw "NullPointerException")
class Obj
{
public:
int x;
void Add(const Obj& obj)
{
this.x += obj.x; // throws "NullPointerException"
//x = obj.x; // throws Access Violation Exception
}
};
void main()
{
Obj *o = new Obj();
Obj *o2 = nullptr;
try
{
(*o2).Add(*o);
}
catch (char *exception)
{
std::cout << exception;
}
getchar();
}
Run Code Online (Sandbox Code Playgroud)因为this永远不可能nullptr,编译器可以自由地对待this != nullptr它们true.你从根本上想要做的事情没有意义.您不能使用异常来捕获未定义的行为.唯一的办法this可以nullptr是通过不确定的行为.
Obj *o2 = nullptr;
try
{
(*o2).Add(*o);
}
Run Code Online (Sandbox Code Playgroud)
取消引用a nullptr是未定义的行为(8.3.2).这是试图使用异常来捕获未定义的行为.从根本上说,你不能用C++做到这一点.
由于一个明显的原因,这是未定义的,请考虑这个:
class Foo
{
public:
Foo { ; }
virtual void func() = 0;
};
class Bar : public Foo
{
public:
Bar() { ; }
virtual void func() { some_code() }
};
class Baz : public foo
{
public:
Baz() { ; }
virtual void func() { some_other_code(); }
}
...
Foo * j = nullptr;
j->func(); // Uh oh, which func?
Run Code Online (Sandbox Code Playgroud)