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

后端 未结 6 1126
半阙折子戏
半阙折子戏 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:46

    When you throw an exception, the object you're throwing generally resides on the stack. The stack is getting cleaned up as part of the process of throwing, so the compiler must make a copy that can continue to live beyond that point.

    When you throw an object with new, you're not throwing the actual object but you're throwing a pointer to the object. That means your catch block must also catch a pointer rather than a reference. Don't forget to delete the pointer or you'll have a memory leak!

    When the catch block uses throw; instead of throw e; it can reuse the copy it made earlier and there's no need to make another copy.

提交回复
热议问题