gpt4 book ai didi

c++ - "throw MyException()"和 "throw (MyException())"之间有区别吗?

转载 作者:行者123 更新时间:2023-12-03 06:50:06 26 4
gpt4 key购买 nike

我想知道编写异常收件箱和发件箱是否会改变特定程序的行为,例如 抛出 MyException(); 抛出(我的异常());
我的代码:

#include <iostream>
#include <exception>
using namespace std;

class MyException: public exception {
public:
virtual const char* what() const throw()
{
return "Something bad happened";
}
};
class Test
{
public:
void goWrong()
{
throw (MyException());
}
};

int main()
{
Test test;
try
{
test.goWrong();
}
catch (MyException &err)
{
cout << "The Exception is Executed: " << err.what() << '\n';
}
cout << "Still Running" << '\n';
return 0;
}

最佳答案

异常对象是复制初始化的( except.throw/3 ),因此您使用哪个并不重要;结果是一样的。
即使您从中得到了一个,复制初始化也会忽略引用限定符。
我们可以用一些跟踪输出来证明这一点:

#include <cstdio>
using std::printf;

struct T
{
T() { printf("T()\n"); }
~T() { printf("~T()\n"); }
T(const T&) { printf("T(const T&)\n"); }
T(T&&) { printf("T(T&&)\n"); }
T& operator=(const T&) { printf("T& operator=(const T&)\n"); return *this; }
T& operator=(const T&&) { printf("T& operator=(T&&)\n"); return *this; }
};

int main()
{
try
{
throw T();
}
catch (const T&) {}
}
即使您从 throw T() 切换至 throw (T())语义(和输出)完全相同:
T()
T(T&&)
~T()
~T()
即临时 T()被构造,然后移动到真正的异常对象(它存在于某个神奇的“安全空间”中),最终两者都被破坏。
请注意,要查看此证明,您必须返回到 C++14(因为 C++17 不会在需要真正的异常对象之前实现该临时对象,即所谓的“强制省略”)并转关闭 pre-C++17 可选省略(例如 GCC 中的 -fno-elide-constructors)。
如果像其他一些人声称的那样,可能存在诸如“抛出引用”(变得悬空)这样的事情,那么您只会看到 T 的一个结构。 .事实上,尽管 decltype 尽了最大努力,但并不存在引用类型表达式这样的东西。和 auto假装你有。
在这两种情况下,我们给 throw 的表达式是一个右值 MyException .
我们必须小心 return的原因当使用推导的返回类型(通过 decltype(auto) )时,推导是否考虑值类别。如果你有一个局部变量 int x ,然后在 return x表达式 x是 xvalue int ,所以你推导出的类型将是 int一切都很好。如果你写 return (x)相反,表达式是左值 int ,这导致推导出的类型 int&突然间你有问题。请注意 neither expression has reference type ( a thing which effectively does not exist )。但这一切都与您的 throw 无关。无论如何,尤其是因为您的论点首先是暂时的。

关于c++ - "throw MyException()"和 "throw (MyException())"之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64790947/

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