在使用异常时,如何保护自己免受未完全创建的对象的侵害?我应该加入构造函数吗?还是不好的做法?如果我陷入困境,构造器对象将被创建。
#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)
};
语言本身不具有对象以任何可检测的方式“无效”的概念。
如果异常指示无法创建有效对象,则不应在构造函数中对其进行处理;要么将其扔掉,要么就不要将其抓到。然后,程序将离开正在创建的对象的范围,并且将不可能错误地访问它。
如果由于某种原因这不是一个选择,那么您将需要用自己的方式将对象标记为“无效”。也许在构造函数的末尾设置一个布尔成员变量以指示成功。这很容易出错,因此除非您有充分的理由,否则不要这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句