Gri*_*ner 7 c++ const exception
请使用以下代码;
void DoThrow( const std::exception& e )
{
throw e;
}
int main( int nArgs, char* args[] )
{
std::exception e;
try
{
DoThrow( e );
}
catch( std::exception& e )
{
// const exception ref is caught
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试在我的项目中改进const正确性并且无意中创建了上述情况.就目前而言,在Dev Studio中,catch块可以捕获异常,尽管事实上它被抛出为const&但是被捕获为非const&.
问题 - 应该吗?:-)
throw获取表达式并通过复制初始化创建基于该表达式的静态类型的异常对象.异常对象不是const对象.
该catch语句初始化对异常对象的引用,而不是throw表达式引用的对象(如果有).