用 noexcept 重写 throw after 函数

rewrite throw after function with noexcept

我听说在 C++11 中我们应该在方法声明后用 noexcept 替换 throw :

In C++11, you generally should use noexcept instead. The old throw specification is deprecated.

下面的代码是怎么做的?

template <typename Object>
class Stack
{
public:

    Stack();

    Object & peek() throw(std::runtime_error);

};

引用link

请避免链接到不适用于 std::runtime_error

的问题

我们发现动态异常规范并不是真正有用,这就是它们在 C++11 中被弃用的原因。它们被认为有用的唯一情况是 动态异常规范,即 throw()。对于这种情况,引入 noexcept 声明作为更好的选择,允许编译器执行更积极的优化。 (请注意,这意味着 throw()noexcept 在语义上 而不是 是等价的,如果您知道该程序仍会运行,则只应将前者替换为后者正确。)

在你的例子中,你没有空的 throw(),所以你不能用 noexcept 替换它。人们普遍认为,在这种情况下,最好简单地删除 throw(std::runtime_error) 并提及该函数可能会抛出 std::runtime_error 但文档中没有其他内容的事实,因为 Yakk 已经在评论中提出了。