抛出自定义空指针异常
throwing custom null pointer exception
是否有一种简单的方法在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(); }
由于this
永远不可能是nullptr
,编译器可以自由地将this != nullptr
视为true
。你想做的事情根本没有意义。您不能使用异常来捕获未定义的行为。this
可以成为nullptr
的唯一途径是通过未定义行为。
Obj *o2 = nullptr;
try
{
(*o2).Add(*o);
}
解引用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?
相关文章:
- 如何使用 C 指针的自定义删除器创建unique_ptr?
- 基于范围的 for 循环,用于包含C++中的指针的自定义链表,仅返回对象
- 如何正确使用带有智能指针和自定义类的映射作为键和值
- 包含其他类的指针的自定义类的向量
- 通过指针填充自定义的类 - 与构造函数的麻烦
- 带有空指针的自定义内存
- 如何编写一个可以接受函数指针和/或函子的类,就像智能指针对自定义deleter所做的那样
- 我需要共享指针的自定义分配器吗
- 通过多态性和指针C++自定义异构容器
- 返回空指针的用户定义运算符new
- 为什么 std::shared_ptr 取消引用不会引发空指针异常(或类似异常)?
- C++——智能指针和自定义内存分配困境
- 正在为共享指针调用自定义deleter类成员函数
- std::唯一指针和自定义lambda删除器错误
- deque中指针的自定义比较器
- 指针,自定义类,第11节错误
- 自动调用原始指针的自定义转换器 A* <-> B*
- 为什么解引用空指针是未定义的行为
- 在JNI对话框生成器调用中出现空指针异常
- 抛出自定义空指针异常