Oli*_*liv 5 c++ new-operator dynamic-memory-allocation delete-operator
如果我将operator delete定义为如下,并且如果对象构造函数抛出新表达式,我希望看到调用定义的运算符的结果delete:
#include <new>
#include <cstdlib>
#include <iostream>
void*
operator new(std::size_t s){
std::cout << "alloc " << std::endl;
return std::malloc(s);
}
void
operator delete(void* p) noexcept {
std::cout << "dealloc " << std::endl;
std::free(p);
}
void
operator delete(void* p,std::size_t) noexcept{
std::free(p);
std::cout << "dealloc s" << std::endl;
}
struct A{
A(int i){
if(i>0)
throw 10;
}
};
int main(int argc// will equal 10
,char* arg[])
{
for(int i=0;i<argc;++i)
auto p=new A{argc};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个程序刚输出alloc,为什么不调用operator delete?在标准[expr.new]中指定:
如果上述对象初始化的任何部分通过抛出异常终止并且可以找到合适的释放函数,则调用释放函数以释放构造对象的内存,之后异常继续在上下文中传播.新表达的.
如果您修复代码以引发异常,它将按预期工作:
int main(int argc,char* arg[])
{
try {
new A(2);
}
catch (...)
{}
}
Run Code Online (Sandbox Code Playgroud)