gpt4 book ai didi

c++ - 如何从构造函数返回错误代码?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:34 25 4
gpt4 key购买 nike

我试图从构造函数返回错误代码,因为构造函数不返回错误代码,我试图在构造函数。然后在 catch block 中,我返回适当的错误代码。这是从构造函数返回错误代码的正确方法吗?

#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;
}

最佳答案

根据 isocpp.org ,在 C++ 中处理构造函数失败的正确方法是:

Throw an exception.

不可能使用错误代码,因为构造函数没有返回类型。但是:

If you don’t have the option of using exceptions, the “least bad” work-around is to put the object into a “zombie” state by setting an internal status bit so the object acts sort of like it’s dead even though it is technically still alive.

但是如果可以的话,你真的应该使用异常来表示构造函数中的失败,如前所述:

In practice the “zombie” thing gets pretty ugly. Certainly you should prefer exceptions over zombie objects, but if you do not have the option of using exceptions, zombie objects might be the “least bad” alternative.

关于c++ - 如何从构造函数返回错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45643859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com