c++ - 构造函数的函数尝试 block 的处理程序中的返回语句

标签 c++

请举个例子帮助理解下面的内容

来自 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-blocktry将函数或构造函数的整个外部包装起来的 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/

相关文章:

c# - 避免我的应用程序使用打印屏幕进行捕获

c++ - 交换 C++ 数组的 2 个字符

c++ - C2059 语法错误 'string' ?

c++ - MPI_Dims_create 在远程机器上抛出错误

c++ - 是否可以使用 SFML 绘制曲线?

c++ - 实现合并排序代码时无法计算所有反转

c++ - std::array 成员函数 empty()、max_size() - 无用但为了一致性?

c++ - 计算给定数字列表的四分位数

c++ - 在 C++ 中不使用 char 类型定义 '999e999' 值

C++:访问由另一种方法返回的 vector 的常量 vector 时出现段错误