开发者

Struct base class as throw exception object

Intuition tells me the simpler the thrown type, the better. Better throw an int than a pointer, better throw a struct than a class. In this case though it is necessary to throw an almost full class with dynamically allocated members. It is convenient to allocate memory in the heap because buffers may become quite long and copying be expensive; it need not have methods because it acts as a control/argument struct for other objects, but it is convenient to both build it in the heap to throw a pointer to struct and to have a destructor to clean up memory. The simpler the better, so should the destructor be virtual? Is it better to omit a vtable or vtables do not affect at all exception passing?

The advantage of deriving classes from this struct as base class would be to add more data, not to polymorph methods. The pointer may potentially be caught several layers ahead from the exception point and be passed among modules, so the object should behave as clean as possible and have 开发者_Python百科as little risk of compounding errors as possible.


Have a look at std::exception and inherit from that.

A destructor should only be virtual if you expect people to use the class as a base class.


A virtual destructor is only necessary when deleting an object via a pointer to a base class. In the case of exception types, you should not be creating them dynamically, but throwing by value. So there is no need to delete them, via a base class pointer or otherwise, and so no need for a virtual destructor.

Having said that, the cost of a v-table is small compared with the dynamically-allocated data you mention, and compared with the cost of throwing an exception at all, and you should always favour utility over efficiency unless there's a proven need to optimise. I would recommend you derive all your exception types from std::exception so that you can handle errors thrown by both your code and the standard library (and other libraries) in a uniform way. This already has a virtual function (what(), returning a message string) and a virtual destructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜