【发布时间】:2018-02-10 06:01:59
【问题描述】:
如果我将 operator delete 定义如下,并且如果对象构造函数抛出 new 表达式,我希望看到调用定义的 operator 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;
}
这个程序只是输出alloc,为什么没有调用操作符delete?在标准 [expr.new] 中规定:
如果上述对象初始化的任何部分通过抛出异常和合适的 可以发现deallocation函数,调用deallocation函数释放对象所在的内存 正在构造,之后异常继续在 new-expression 的上下文中传播。
【问题讨论】:
-
你没有 try catch 块。
-
@Jarod42 你是对的!谢谢!我需要 catch 块,因为存在异常的主要功能是 UB 还是出于其他先前的原因?
-
用于UB部分。顺便说一句,
return i;无效(i超出范围)。 -
@Jarod42:这不是 UB。当未捕获到异常时,调用 std::terminate。
-
argc的值是多少?我想是 1,所以你不会抛出异常。
标签: c++ new-operator dynamic-memory-allocation delete-operator