What's the best technique for exiting from a constructor on an error condition in C++

后端 未结 8 867
北荒
北荒 2020-12-14 08:21

What\'s the best technique for exiting from a constructor on an error condition in C++? In particular, this is an error opening a file.

Thanks for the responses. I\'

8条回答
  •  半阙折子戏
    2020-12-14 08:37

    If the object that you're constructing is invalid due to the error, and needs to be disposed of by the caller, then you pretty much have to throw an exception. This allows the compiler to perform the proper deallocation of resources.

    (Writing exception-safe constructors requires a bit of care -- in brief, you need to use the initializer lists wherever you can, rather than using the constructor body -- but it's critical if you have a case like this, where throwing an exception is a significant possibility.)

提交回复
热议问题