函数声明后的 throw() 有什么用?

Min*_*ham 2 c++

C++ expressionThrow在https://en.cppreference.com/w/cpp/language/throw中定义为 a 。从语法上讲,它后面跟着一个异常类名。例如:

int a = 1, b = 0; 
if (b==0){
    string m ="Divided by zero";
    throw MyException(m);       //MyException is a class that inherit std::exception class
}
Run Code Online (Sandbox Code Playgroud)

但是,我见过其他一些我不太理解的 throw 语法:

void MyFunction(int i) throw();     // how can we have an expression following a function definition? 
Run Code Online (Sandbox Code Playgroud)

或者在自定义异常类中,我们还有:

class MyException : public std::exception
{
public:
  MyException( const std::string m)
    : m_( m )
  {}

  virtual ~MyException() throw(){};               // what is throw() in this case? 
  const char* what() const throw() {                       // what are the parentheses called? 
      cout<<"MyException in ";
      return m_.c_str(); 
  }

private:
  std::string m_;
};
Run Code Online (Sandbox Code Playgroud)

因此,我的问题是:

  1. 是否存在允许表达式后跟函数定义的通用语法规则?
  2. 为什么表达式抛出后有括号?它们在 C++ 中叫什么?

use*_*522 6

throw()不是一个throw表达式。它是一个完全独立的语法结构,只是碰巧看起来相同(C++ 喜欢为了多种目的而重用关键字,而不是保留更多标识符)。示例中使用的位置throw()不是语言语法期望表达式的位置,因此它不能是表达式throw。此外也不是有效的表达式(如表达式中()所要求的那样)。throwthrow

它是为函数声明不抛出动态异常规范的语法,这意味着它声明该函数不会抛出任何异常。

该语法自 C++11 起已被弃用,并最终在 C++20 中完全从语言中删除。因此不应再使用它。

动态异常规范的确切机制没有替代品,但具体来说,非抛出声明throw()已被noexcept说明符取代(自 C++11 起)。throw()因此,旧代码中函数声明上的所有使用都应更新为noexcept