且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理构造函数中的错误值?

更新时间:2023-01-12 14:57:20

典型的解决方案是抛出异常.

The typical solution is to throw an exception.

其背后的逻辑如下:构造函数是一种将内存块转换为有效对象的方法.要么它成功(正常完成)并且您有一个有效的对象,要么您需要一些不可忽视的问题指示符.异常是使问题在 C++ 中不可忽略的唯一方法.

The logic behind that is the following: the constructor is a method that transforms a chunk of memory into a valid object. Either it succeeds (finishes normally) and you have a valid object or you need some non-ignorable indicator of a problem. Exceptions are the only way to make the problem non-ignorable in C++.