gpt4 book ai didi

c++ - try catch 语法构造函数

转载 作者:可可西里 更新时间:2023-11-01 18:19:51 26 4
gpt4 key购买 nike

http://ideone.com/UtVzxw

struct base
{
base() { throw std::exception(); }
};

struct derived : public base
{
derived() try : base() { }

catch (std::exception& e)
{
std::cout << "exception handled" << std::endl;
}
};

int main()
{
derived a; // My app crashes.
return 0;
}

我的应用程序不应该写“异常处理”并继续运行吗?

我找到的唯一解决方案是在 try/catch block 中包围“a”的构造。但是如果我这样做,那么首先在构造函数中使用 try/catch 有什么意义呢?我猜也许它的用途是清理可能已分配的成员变量?因为没有调用析构函数

以下有效,但处理了 2 次异常。

struct base
{
base() { throw std::exception(); }
};

struct derived : public base
{
derived() try : base() { }

catch(std::exception& e)
{
std::cout << "exception 1" << std::endl;
}
};

int main()
{
// This works fine.
try {
derived a;
}
catch(std::exception& e)
{
std::cout << "exception 2" << std::endl;
}
return 0;
}

我只是想问问自己为什么我不应该简单地避开构造函数的 try/catch 语法并写下这个:

struct base
{
base() { throw std::exception(); }
};

struct derived : public base
{
derived() : base() { }
};

int main()
{
// This works fine.
try {
derived a;
}
catch(std::exception& e)
{
std::cout << "exception handled" << std::endl;
}
return 0;
}

最佳答案

构造函数中的

function-try-block 不会阻止抛出异常。这是 C++ 标准草案 N4140 的摘录,[except.handle]:

14 If a return statement appears in a handler of the function-try-block of a constructor, the program is ill-formed.

15 The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. Otherwise, ...

原因是如果基类或者任何一个成员构造函数抛出异常,那么整个对象的构造就会失败,而且没有办法修复,所以只好抛出异常。

有一个 GOTW在这一点上,底线是

Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other side effects.) They are not useful for any other purpose.

所以,是的,您的最后一个代码示例非常好。

关于c++ - try catch 语法构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com