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

后端 未结 6 1200
半阙折子戏
半阙折子戏 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条回答
  •  北恋
    北恋 (楼主)
    2021-01-07 14:40

    Several points:

    1st of all don't call throw new foo() use throw foo

    2nd when your write:

    catch(foo const &e) {
       throw e;
    }
    

    You actually create a new exception, and if for example the exception that was thrown is subclass of foo they my calling throw e you would loose this information and actually use a copy constructor to generate foo from e - whatever it was.

    Now when you call

    catch(foo const &e) {
       throw;
    }
    

    You don't create a new exception but rather propagate the same exception.

    So: never use throw e; to propagate the exception forward, use throw;

提交回复
热议问题