3 回答

TA貢獻1827條經驗 獲得超8個贊
是的,從失敗的構造函數中引發異常是執行此操作的標準方法。閱讀有關處理失敗的構造函數的常見問題,以獲取更多信息。擁有init()方法也可以,但是創建互斥對象的每個人都必須記住必須調用init()。我覺得這違反了RAII原則。

TA貢獻1895條經驗 獲得超3個贊
如果確實從構造函數引發異常,請記住,如果需要在構造函數初始化器列表中捕獲該異常,則需要使用try / catch語法。
例如
func::func() : foo()
{
try {...}
catch (...) // will NOT catch exceptions thrown from foo constructor
{ ... }
}
與
func::func()
try : foo() {...}
catch (...) // will catch exceptions thrown from foo constructor
{ ... }

TA貢獻1852條經驗 獲得超7個贊
#include <iostream>
class bar
{
public:
bar()
{
std::cout << "bar() called" << std::endl;
}
~bar()
{
std::cout << "~bar() called" << std::endl;
}
};
class foo
{
public:
foo()
: b(new bar())
{
std::cout << "foo() called" << std::endl;
throw "throw something";
}
~foo()
{
delete b;
std::cout << "~foo() called" << std::endl;
}
private:
bar *b;
};
int main(void)
{
try {
std::cout << "heap: new foo" << std::endl;
foo *f = new foo();
} catch (const char *e) {
std::cout << "heap exception: " << e << std::endl;
}
try {
std::cout << "stack: foo" << std::endl;
foo f;
} catch (const char *e) {
std::cout << "stack exception: " << e << std::endl;
}
return 0;
}
輸出:
heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something
不會調用析構函數,因此,如果需要在構造函數中引發異常,則需要做很多事情(例如,清理嗎?)。
- 3 回答
- 0 關注
- 530 瀏覽
添加回答
舉報