【发布时间】:2020-10-25 08:26:27
【问题描述】:
我来自 c++98,我正在尝试进入 c++11 等等。我遇到了公共成员函数,std::exception::what, virtual const char* what() const noexcept;
从这个例子中给出的 c++ 参考:what_example,我可以理解用法,但我有几个问题:
// exception::what
#include <iostream> // std::cout
#include <exception> // std::exception
struct ooops : std::exception {
const char* what() const noexcept {return "Ooops!\n";}
};
int main () {
try {
throw ooops();
} catch (std::exception& ex) {
std::cout << ex.what();
}
return 0;
}
- 在 c++98 中,what() 为:
virtual const char* what() const throw();,而在 c++11 中,它变为virtual const char* what() const noexcept;。最后的noexcept是什么?有没有带来新的东西? - 我为什么要使用
what()呢?我可以在我的类异常中实现我自己的tostring方法并调用它! - 在what() 的返回值中,见下文,保证至少在...或直到调用异常对象的非常量成员函数之前有效。 或直到调用异常对象的非常量成员函数是什么意思,有人可以举例解释一下吗?为什么会这样?
what() return value
指向带有异常相关内容的 c 字符串的指针。这是 保证至少在异常对象之前有效 它被销毁或直到一个非常量成员函数 异常对象被调用。
谢谢。
【问题讨论】:
-
请不要同时提出多个问题。尤其是当他们每个人都可以被自己的 SO 帖子覆盖时。第一个是stackoverflow.com/questions/12833241/…的副本
-
@StoryTeller-UnslanderMonica-也许在您附加的链接中他们有部分答案,但这仍然不能回答我的问题。
标签: c++ c++11 exception noexcept