考虑这个例子:
struct Nobody_Expects_The_Spanish_Inquisition{};
int main(){
throw Nobody_Expects_The_Spanish_Inquisition();
}
输出显示在 Ideone 上:
terminate called after throwing an instance of Nobody_Expects_The_Spanish_Inquisition'
Windows 的类似输出:
Unhandled exception at 0x760fb727 in Test.exe: Microsoft C++ exception: Nobody_Expects_The_Spanish_Inquisition at memory location 0x001ffea3..
可以看出,最终的程序集似乎已经包含了异常的名称,或者有其他方法获取该名称。
这可以看作是某种反射(reflection)吗?或者是否可以实际显示异常名称是否取决于编译器/操作系统?
最佳答案
它依赖于编译器。显然,编译器很容易发现每次抛出,并将每个抛出对象的类型编码到可执行文件中。但是没有要求他们应该这样做。
考虑一下,当抛出异常时,必须将异常复制到一个奇怪的依赖于实现的空间中。因此,通过这种机制,特定编译器的运行时可以访问它们的类型名称是有道理的。
关于c++ - C++ 是否已经有了某种反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6312493/