对象内存模型的问题: 对象数组的构造过程如果失败了,被构造的对象会被析构么?
<<深入理解C++对象内存模型>>这本书上对于对象数组的构造是这样解释的,编译器会把ctor/dtor的地址都push到堆栈上,作为一个编译器生成的函数参数:
object *pobj=new object[some];会让编译器产生一个函数:
void objectArrayCtor( (void)(*pCtor)(), (void)(*pDtor), object* pMem, size_t nCount ){ try{ for(int c=0;c<nCount;++c){ pMem[c]->object::object();//构造函数调用 } }...}
object *pobj=operator new(some* sizeof(object));objectArrayCtor( &object::object, &object::~object, pobj, some);
#include<stdexcept>using namespace std;struct s{ static int s_count; int i; s() { ++s_count; printf("ctor %d,%p\n",s_count,this); try{ if(s_count==5)throw std::range_error("divide 0!"); i=10/(s_count-5); //divide by 0 when s_count=5 } catch(exception& e){ throw e; } } ~s() { printf("dtor %p\n",this); }};int s::s_count=0;int main(int,char*[]){ s* ps=new s[10]; delete[]ps; return 0;}
#include<stdexcept>using namespace std;struct s{ static int s_count; int i; s() { ++s_count; printf("ctor %d,%p\n",s_count,this); try{ if(s_count==5)throw std::range_error("divide 0!"); i=10/(s_count-5); //divide by 0 when s_count=5 } catch(exception& e){ throw e; } } ~s() { printf("dtor %p\n",this); }};int s::s_count=0;int main(int,char*[]){ try { s* ps=new s[10]; delete[]ps; } catch (...) // stack unwinding happened before this point. { } return 0;}