c++ - 重载 operator new

c++ - overloading operator new

我对运算符重载 new 和 delete 有点困惑。 我写了一些测试:

#include <iostream>

using namespace std;

class Test
{
    public :

    Test()
    {
        cout << "Test - ctor" <<endl;
    }

    ~Test()
    {
        cout << "Test - dtor" <<endl;
    }

    Test(const Test& t)
    {
        cout << "Test - copy ctor" <<endl;
    }

    Test& operator = (const Test& t)
    {
        cout << "Test - assiment operator" <<endl;
    }

    void* operator new(size_t size)
    {
        cout << "Test - operator new" <<endl;
        return NULL;
    }

    void print()
    {
        cout << "print" << endl;
    }
};


int main()
{
   Test* t = new Test();
   t->print();
   return 0;
}

输出为:

Test - operator new                                                                                                                                                                                
Test - ctor                                                                                                                                                                                        
print  

现在,如果我从 "new" return "NULL" 调用打印函数,为什么我的程序没有崩溃? 谢谢。

因为 print() 实际上不需要它的任何东西 class Test。它所做的只是向 stdout 打印一条消息。请记住 t->print();print(t); 相同,您的函数签名实际上是:

void print(Test* t);

但这都是编译器为您完成的。

t 只是没有在方法中使用,因此你很(不)幸运,因为它运行了。不过,这仍然只是普通的未定义行为。

如果你绝对想看到事情崩溃和燃烧然后改变你的 class 一点:

class Test
{
    public :

    Test() : x(0)
    {
        cout << "Test - ctor" <<endl;
    }

    ~Test()
    {
        cout << "Test - dtor" <<endl;
    }

    Test(const Test& t)
    {
        cout << "Test - copy ctor" <<endl;
    }

    Test& operator = (const Test& t)
    {
        cout << "Test - assiment operator" <<endl;
    }

    void* operator new(size_t size)
    {
        cout << "Test - operator new" <<endl;
        return NULL;
    }

    void print()
    {
        cout << "print" << x << endl;
    }

private:
    int x;
};

此具体现象与您的operator new功能无关。

通过 NULL 指针调用成员函数的行为是未定义。你的结果是这种未定义行为的表现。

它恰好适用于您的特定情况(可能是因为您的 class 只是一堆函数)。

(这些天使用 nullptr 比老式且不完全正确的 NULL 是个好主意。)