【发布时间】:2016-10-07 09:28:25
【问题描述】:
我对运算符重载 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" 返回 "NULL" ,为什么我调用 print 函数时程序不会崩溃? 谢谢。
【问题讨论】:
-
这与过载无关,它是常规的未定义行为。试试
Test* t = nullptr; t->print();看看会发生什么(或没有)。 -
UB 和 UB 一样。
标签: c++ operator-overloading new-operator