在使用异常时如何保护自己不使用未完全创建的对象? 我应该捕获构造函数吗?或者这可能是不好的做法?如果我在构造函数中捕获,将创建对象。
#include <stdio.h>
class A
{
public:
A()
{
try {
throw "Something bad happened...";
}
catch(const char* e) {
printf("Handled exception: %s\n", s);
}
// code continues here so our bad/broken object is created then?
}
~A()
{
printf("A:~A()");
}
void Method()
{ // do something
}
};
void main()
{
A object; // constructor will throw... and catch, code continues after catch so basically we've got
// broken object.
//And the question here:
//
//* is it possible to check if this object exists without catching it from main?
// &object still gives me an address of this broken object so it's created but how can I protect myself
// from using this broken object without writing try/catch and using error codes?
object.Method(); // something really bad. (aborting the program)
};
最佳答案
语言本身没有以任何可检测的方式“无效”对象的概念。
如果异常指示无法创建有效对象,则不应在构造函数中处理它;要么重新扔掉它,要么一开始就不要捕获它。然后程序将离开正在创建的对象的范围,并且将不可能错误地访问它。
如果出于某种原因这不是一个选项,那么您将需要自己的方式将对象标记为“无效”;也许在构造函数的末尾设置一个 bool 成员变量以指示成功。这是不稳定且容易出错的,所以除非你有充分的理由,否则不要这样做。
关于C++ 在构造函数中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26169189/