有没有一种简单的方法可以在 C++ 中引发自定义空指针异常?我的想法是重新定义this
指针,但它有3个问题:
- 不使用
this
会引发标准访问冲突异常 - 每次使用时都会检查指针
Visual 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(); }