请举个例子帮助理解下面的内容
来自 C++ n45277:$15.3 - 13
If a
return
statement appears in a handler of the function-try-block of a constructor, the program is ill-formed.
这是否意味着在构造函数中使用 return
??
谢谢
最佳答案
A function-try-block是 try
将函数或构造函数的整个外部包装起来的 block ,而不仅仅是主体内部的一段代码。
对于构造函数,它允许您捕获在初始化列表 中初始化基类和数据成员时抛出的异常。如果抛出这样的异常,你可以catch
它并根据需要处理错误,但你不能 return
来自 catch
堵塞。当执行到 catch
结束时 block ,当前异常会自动重新抛出。在 catch
之前输入时,在抛出初始异常之前成功构造的任何基类和数据成员都已被破坏以防止泄漏。
正如标准所说:
If a
return
statement appears in a handler of the function-try-block of a constructor, the program is ill-formed.
在这种情况下,处理程序 指的是 catch
try
的 block block 。
例如:
int checkValue(int value)
{
if (value == 1)
throw std::runtime_error("illegal value");
return value;
}
struct A
{
std::string str;
int value;
A(int i) try : str("hello"), value(checkValue(i))
{
// constructor body here ...
// 'return' is OK here!
}
catch (...)
{
// do something here (log the error, etc)...
// 'return' is illegal here!
}
};
注意 try
在初始化列表之前,构造函数的主体在try
内部 block 。
如果checkValue()
抛出异常,构造A
中止,自动销毁str
在此过程中。
您可以在不使用函数尝试 block 的情况下完成同样的事情:
int checkValue(int value)
{
if (value == 1)
throw std::runtime_error("illegal value");
return value;
}
struct A
{
std::string str;
int value;
A(int i)
{
try
{
str = "hello";
value = checkValue(i);
// 'return' is OK here!
}
catch (...)
{
// do something here (log the error, etc)...
// 'return' is OK here! But then the constructor
// would not be aborted...
throw;
}
}
};
通常使用 function-try-block 的地方是当您想要捕获/记录在正常构造函数中无法调用的事物中抛出的异常时 body,仅在初始化列表中,如基类构造函数和数据成员构造函数。
关于c++ - 构造函数的函数尝试 block 的处理程序中的返回语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32383461/