抛出自定义空指针异常

throwing custom null pointer exception

本文关键字:空指针异常 自定义      更新时间:2023-10-16

是否有一种简单的方法在c++中抛出自定义空指针异常?我的想法是重新定义this指针,但它有3个问题:

  1. 不使用this抛出标准访问违反异常
  2. 每次使用指针时检查
  3. 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?