C++: Throwing an exception invokes the copy constructor?

后端 未结 6 1158
半阙折子戏
半阙折子戏 2021-01-07 14:02

We have an custom error class that is used whenever we throw an exception:

class AFX_CLASS_EXPORT CCLAError : public CObject

It has the fol

6条回答
  •  梦毁少年i
    2021-01-07 14:43

    It appears that you have misunderstood what re-throw means. When you do -

    catch(CCLAError& e)
    {
       throw e;
    }
    

    -- you are NOT rethrowing. Instead, as you have observed, you are indeed creating a copy of the new exception. Instead (again, as you have found for yourself), this is what is technically the correct way to re-throw:

    catch(CCLAError& e)
    {
       throw;
    }
    

    Read chapter 14 in Stroustrup's TC++PL (14.3.1 deals with rethrowing).

    Also, you do NOT have to do -

    throw new CCLAError( ... )
    

    Instead, do -

    throw CCLAError( ... )
    

    -- like you were doing before, only receive by CONST reference (you cannot hold a reference to a temporary).

    catch(const CCLAError &e)
    

提交回复
热议问题