我试图从构造函数返回错误代码,因为构造函数不返回错误代码,所以我试图在构造函数上放置一个异常。然后在 catch 块中,我返回相应的错误代码。这是从构造函数返回错误代码的正确方法吗?
#include <exception>
#include <iostream>
class A {
public:
A() { throw std::runtime_error("failed to construct"); }
};
int main() {
try {
A a;
} catch (const std::exception& e) {
std::cout << "returining error 1 \n";
return 1;
}
return 0;
}
原文由 vanta mula 发布,翻译遵循 CC BY-SA 4.0 许可协议
根据 isocpp.org ,在 C++ 中处理构造函数失败的正确方法是:
由于构造函数没有返回类型,因此无法使用错误代码。但 :
但是如果可以的话,你真的应该使用异常来表示构造函数中的失败,如前所述: