简体   繁体   English

抛出异常为const&

[英]Throwing an exception as const&

Take the following code; 请使用以下代码;

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;
}

I'm trying to retrofit const correctness in my project and inadvertently created the above situation. 我正在尝试在我的项目中改进const正确性并且无意中创建了上述情况。 As it stands, in Dev Studio the catch block DOES catch the exception, despite the fact that it is thrown as a const & but caught as a non-const &. 就目前而言,在Dev Studio中,catch块可以捕获异常,尽管事实上它被抛出为const&但是被捕获为非const&。

Question - Should it? 问题 - 应该吗? :-) :-)

throw takes an expression and creates via copy-initialization an exception object based on the static type of that expression. throw接受一个表达式,并通过复制初始化创建一个基于该表达式的静态类型的异常对象。 The exception object is not a const object. 异常对象不是const对象。

The catch statement initializes a reference to the exception object, not the object (if any) referred to by the throw expression. catch语句初始化对异常对象的引用,而不是throw表达式引用的对象(如果有)。

我不知道规范说的是什么,但在我看来,在实践中,使用RTTI将一个异常调度到正确的“catch”块(一些编译器合成代码必须这样做),“const”与之无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM