When is it right for a constructor to throw an exception?

前端 未结 24 982
时光取名叫无心
时光取名叫无心 2020-11-30 16:47

When is it right for a constructor to throw an exception? (Or in the case of Objective C: when is it right for an init\'er to return nil?)

It seems to me that a cons

24条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 17:37

    See C++ FAQ sections 17.2 and 17.4.

    In general, I have found that code that is easier to port and maintain results if constructors are written so they do not fail, and code that can fail is placed in a separate method that returns an error code and leaves the object in an inert state.

提交回复
热议问题