姚雷

构造函数中的异常
姚雷 | May 20, 2008 4:24:38 PM
2.写出下面程序的输出

void* operator new(size_t size)
{
printf("malloc %u\r\n", size);
return malloc(size);
}
void operator delete(void *memblock){
printf("free\r\n");
return free(memblock);
}

class abc{
public:
abc(){
   printf("abc\r\n");
   throw int();
}
~abc(){
   printf("~abc\r\n");
}
};

int main(){
try{
   new abc;
}catch(int& i){
   printf("%d\r\n", i);
}
return 0;
}

此程序考察重载new 与delete以及构造函数抛出异常时C++的处理方式。

打印结果:

malloc 1
abc
free
0

当异常在类的构造函数中被抛出时,编译器认为对象并没有被建立,所以其析构函数不会被执行,但是由于对象是在堆中被建立的,所以编译器会强制调用delete删除掉为其分配的资源。延伸一下:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using std::cout;
using std::endl;

void* operator new(size_t size)
{
printf("operator new malloc %u\r\n", size);
return malloc(size);
}

void operator delete(void *memblock)
{
printf("operator delete free\r\n");
return free(memblock);
}


class A
{
public:
A()
{
   cout<<"A()"<<endl;
}
~A()
{
   cout<<"~A()"<<endl;
}
private:
int i;
};

class abc
{
private:
A a;
public:
abc()
{
   printf("abc()\r\n");
   throw int();
}
~abc()
{
   printf("~abc()\r\n");
}
};


int main()
{
//printf("%d\n",sizeof(abc));
try
{
   new abc;
   //throw 1;
}
catch(int& i)
{
   printf("异常%d\r\n", i);
}
return 0;
}
打印结果:

operator new malloc 4
A()
abc()
~A()
operator delete free
异常0

Comment: (no reply)
To post your comment, Please login first.