为什么它不会进入无限循环
Why it is not going in infinite loop
我是 c++ 的新手,正在尝试 new 和 delete 关键字的运算符重载程序。在探索 Class 特定的重载示例时,我发现了以下程序。
#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
请各位大神指点一下
您的程序不会进入无限循环是因为您在重载 new
运算符的 return
语句中使用范围解析,这意味着您没有在此处调用自己的 new
.
要使其进入无限循环,请将其更改为
return operator new(sz);
希望对您有所帮助。
我是 c++ 的新手,正在尝试 new 和 delete 关键字的运算符重载程序。在探索 Class 特定的重载示例时,我发现了以下程序。
#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
请各位大神指点一下
您的程序不会进入无限循环是因为您在重载 new
运算符的 return
语句中使用范围解析,这意味着您没有在此处调用自己的 new
.
要使其进入无限循环,请将其更改为
return operator new(sz);
希望对您有所帮助。