构造函数中的异常:init()方法,指针,大型try / catch或..?

时间:2018-02-02 14:08:04

标签: c++ exception constructor

我正在处理一个可以抛出错误的对象构造函数。我有以下选择。

1)有一个非常大的try块,它包含了所有需要该对象的代码(因为对象范围):

try {
  Object a(input_vars); // This can throw
  // Do 
  // loads of stuff 
  // with a here
} catch (exception e) {
  // Do something with exception    
}

我对此不太满意,因为它包含非常大的代码部分。不过,这里可能是最吸引人的选择。

2)将throw移动到init()方法:

Object a(input_vars); // This one does not throw
try {
  a.init(); // Only this one can throw
} catch (exception e) {
  // Do something with exception (EDIT: and terminate)
}

// Do some stuff with a
然而,这会导致对象被半结构化,需要人们记住调用init(),并且违反资源获取是初始化(RAII)。

3)仅使用指针:

Object* a;
try {
  a = new Object(input_vars); // This one can throw
} catch (exception e) {
  // Do something with exception (EDIT: and terminate)
}

// Do some stuff with a

delete a;

这需要记住销毁对象。它还会增加指责等风险。

您更喜欢上述哪一个选项?出于哪个原因?还有其他我没想过的选择吗?

1 个答案:

答案 0 :(得分:1)

选项1)是正确的。原因:当构造函数抛出时,对象a无法构造,因此不存在于任何有效状态。使用a的以下代码要么必须一直写成这种可能性,要么最好完全跳过。