-1

有没有一种简单的方法可以在 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();
    }
    
4

1 回答 1

6

由于thiscan never, ever be ,编译器可以自由地nullptr对待. 你试图做的事情根本没有意义。您不能使用异常来捕获未定义的行为。唯一的方法是通过未定义的行为。this != nullptrtruethisnullptr

Obj *o2 = nullptr;
try
{
    (*o2).Add(*o);
}

取消引用 anullptr是未定义的行为 (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?
于 2013-01-15T18:32:30.733 回答