http://ideone.com/UtVzxwてみキャッチシンタックスコンストラクタ
struct base
{
base() { throw std::exception(); }
};
struct derived : public base
{
derived() try : base() { }
catch (std::exception& e)
{
std::cout << "exception handled" << std::endl;
}
};
int main()
{
derived a; // My app crashes.
return 0;
}
は私のアプリの書き込み "の例外が処理さ" と実行を継続Shoun't?
私が見つけた唯一の解決策は、 "a
"の構成をtry/catchブロックで囲むことです。しかし、もし私がそうしたら、最初にコンストラクタにtry/catchを持つのは何ですか?私は多分それが割り当てられているかもしれないメンバー変数をクリーンアップすることです使用していると思いますか? デストラクタが呼び出されていないためですか?
以下は動作しますが、例外を2回処理します。
struct base
{
base() { throw std::exception(); }
};
struct derived : public base
{
derived() try : base() { }
catch(std::exception& e)
{
std::cout << "exception 1" << std::endl;
}
};
int main()
{
// This works fine.
try {
derived a;
}
catch(std::exception& e)
{
std::cout << "exception 2" << std::endl;
}
return 0;
}
私はちょうど私が単にコンストラクタのtry/catch構文をかわすと、これを書いてはならない理由を自問しようとしている:
スーパークラスのコンストラクタ周りのtry/catchをラッピングstruct base
{
base() { throw std::exception(); }
};
struct derived : public base
{
derived() : base() { }
};
int main()
{
// This works fine.
try {
derived a;
}
catch(std::exception& e)
{
std::cout << "exception handled" << std::endl;
}
return 0;
}
Googleでは、例外を使用しないというポリシーがあり、クールなライブラリを見つけましたが、コンストラクタでのみスローされたクラスを継承したいクラスは他にはありません。それを継承する場合は、派生クラスを使用するすべての人が毎回try/catchを使用する必要があります。あなたはその場合何をしますか?唯一の答えは次のようなものです:コンストラクタのために別のライブラリを使用してください。 – James
@Phantomまたはそれを継承しないで、そのメンバーへのポインタを作成し、コンストラクタ本体で初期化します。しかし、私はGoogleであなたがそのライブラリを使用することを許可しないと信じています。 –