如果我定義的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
,爲什麼運營商刪除不叫?在標準的[expr.new]它被指定的是:
如果上述對象初始化的任何部分通過拋出異常和合適 釋放函數可以發現終止,解除分配函數被調用,以自由其中正在構造對象 的內存,之後異常繼續在新表達式的上下文中傳播。
您沒有try catch塊。 – Jarod42
@ Jarod42你是對的!謝謝!我需要catch catch,因爲生活的主要功能是UB,還是出於其他原因? – Oliv
這是UB部分。順便說一句,'return i;'是無效的('i'超出了範圍)。 – Jarod42