C 如何寫出異常安全的建構函式?

時間 2021-06-03 15:00:55

1樓:黃亮anthony

在main中增加乙個catch子句就可以得到你想要的結果。

intmain

()catch

(...)

return0;

}輸出A::constructor.

B::constructor.

C::constructor.

D::constructor.

C::destructor.

B::destructor.

2樓:XZiar

#include

#include

#include

structA~

A()};int

main

()會輸出什麼?

Start

terminate called after throwing an instance of 'std::runtime_error'

what(): runtime_error

AAborted

Finish

所以,我覺得只是因為編譯器發現沒有catch,就放棄析構了;或者析構是發生在catch之後的

畢竟如果不catch,整個程序直接崩了,也沒有「清理資料」的必要了吧。

根據Are destructors called after a throw in C++?

有這麼一條規則:

C++1115.5.1 The std::terminate() function [except.terminate]

2 … In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called.

沒找到exception handler的話,可以不進行stack unwind。

C 的預設建構函式,複製建構函式 有無 const ,成員型別變成 no class type ?

叛逆者 既然你要的是拷貝構造,為什麼不就好好的按照拷貝構造的規範來,引數老老實實用const T 而要T Detail 這種臨時物件,你難道想改不成。std string型別的引數,要const 或者 從初學就該養成這樣的好習慣。operator 的引數也要是const。也是從初學就該養成這樣的好習...

c 關於複製建構函式的使用?

首先前兩次是因為 Line line myp1,myp2 這個建構函式是這樣的 Line Line Point xp1,Point xp2 p1 xp1 p2 xp2 可以看出是把物件按值傳入,所以編譯器可能會完成下面的操作 Point temp1 xp1 Point temp2 xp2 呼叫構造拷...

c 中,如果建構函式構造失敗,如何終止並且不建立物件?

已登出 方案一 class Foo public explicit Foo int arg if arg 0 throw ERROR BADARGUMENTS 方案二,構造前判斷,失敗返回nullptr class Foo private explicit Foo int arg public st...