この質問は、この質問とコメントによるものです。
この例:
#include <iostream>
struct A {
A(int value) : m_value(value) { }
int m_value;
};
struct B : A {
B(int value) : A (value) { }
};
int main()
{
try {
throw B(5);
}
catch(A) {
std::cout << "A catch" << std::endl;
}
catch(B) {
std::cout << "B catch" << std::endl;
}
}
このようにg ++ 4.6.1を使用してコンパイルすると:
g++ exception_slicing.cpp -ansi -pedantic -Wall -Wextra
次の出力を生成します:
exception_slicing.cpp: In function 'int main()':
exception_slicing.cpp:20:5: warning: exception of type 'B' will be caught [enabled by default]
exception_slicing.cpp:17:5: warning: by earlier handler for 'A' [enabled by default]
出力はA catch
です。
スライスの問題が原因で最初の catch ブロックがトリガーされたことを理解しています。
- 基本クラスの隠しコピー コンストラクターについてはどこに記載されていますか?
- この振る舞いについてどこに書かれていますか?
PS1 規格から引用して回答を提供してください。
PS2そして、例外はconst参照で処理する必要があることを認識しています。