构造函数中的异常

C++语言: Codee#2575201#include

02

03usingnamespacestd;

04

05classTrace

06{

07staticintcounter;

08intobjid;

09public:

10Trace()

11{

12objid=++counter;

13cout<<"constructing Trace #"<<objid<<endl;

14if(objid==3)

15throw3;

16}

17~Trace()

18{

19cout<<"destructing Trace #"<<objid<<endl;

20}

21};

22

23intTrace::counter=0;

24

25intmain()

26{

27try

28{

29Tracen1;

30Tracearray[5];

31Tracen2;

32}

33catch(inti)

34{

35cout<<"caught "<<i<<endl;

36}

37

38return0;

39}

40/

41constructing Trace #1

42constructing Trace #2

43constructing Trace #3 //throw exception before this object was completely constructed!

44destructing Trace #2

45destructing Trace #1

46caught 3

47

48Process returned 0 (0x0) execution time : 0.092 s

49Press any key to continue.

50

51

52

53
/


C++语言: Codee#2575301/

02已经成功构造的cat对象不会被销毁

03导致内存泄漏

04
/

05

06#include

07#include

08usingnamespacestd;

09

10classCat

11{

12public:

13Cat()

14{

15cout<<"Cat()"<<endl;

16}

17~Cat()

18{

19cout<<"~Cat()"<<endl;

20}

21};

22

23classDog

24{

25public:

26voidoperatornew(size_tsz)

27{

28cout<<"allocating a Dog"<<endl;

29throw47;

30}

31voidoperatordelete(void
p)

32{

33cout<<"deallocating a Dog"<<endl;

34::operatordelete(p);

35}

36};

37

38classUseResources

39{

40Catbp;

41Dog
op;

42public:

43UseResources(intcount=1)

44{

45cout<<"UseResources()"<<endl;

46bp=newCat[count];

47op=newDog;

48}

49~UseResources()

50{

51cout<<"~UseResources()"<<endl;

52delete[]bp;

53deleteop;

54}

55};

56

57intmain()

58{

59try

60{

61UseResourcesur(3);

62}

63catch(int)

64{

65cout<<"inside handler"<<endl;

66}

67

68return0;

69}

70/

71UseResources()

72Cat()

73Cat()

74Cat()

75allocating a Dog

76inside handler

77

78Process returned 0 (0x0) execution time : 0.065 s

79Press any key to continue.

80

81

82

83

84

85

86
/原文链接: https://www.cnblogs.com/invisible/archive/2012/03/09/2387228.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/43791

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午8:25
下一篇 2023年2月8日 下午8:26

相关推荐