我是C ++的新手,正在尝试对new和delete关键字进行运算符重载的程序。在研究特定于类的重载示例时,我找到了以下程序。
#include <iostream>
// class-specific allocation functions
struct X {
static void* operator new(std::size_t sz)
{
std::cout << "custom new for size " << sz << '\n';
return ::operator new(sz);
}
static void* operator new[](std::size_t sz)
{
std::cout << "custom new for size " << sz << '\n';
return ::operator new(sz);
}
};
int main() {
X* p1 = new X;
delete p1;
X* p2 = new X[10];
delete[] p2;
}
我对上述程序正在运行感到惊讶。当我们为new和delete关键字编写自己的代码时,同时我们也在使用它。以我的想法,它应该进入无限循环。但是它工作正常。请在下面找到结果。
custom new for size 1
custom new for size 10
请有人对此提出建议。
您的程序不会进入无限循环,因为您在return
重载new
运算符的语句中使用范围解析,这意味着您不会new
在此处调用自己的。
要使其陷入无限循环,请将其更改为
return operator new(sz);
我希望这有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句