简体   繁体   中英

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. 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 &.

Question - Should it? :-)

throw takes an expression and creates via copy-initialization an exception object based on the static type of that expression. The exception object is not a const object.

The catch statement initializes a reference to the exception object, not the object (if any) referred to by the throw expression.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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