何时以及为何实际需要使用 C++ 中的 noexcept?
大家好!我写 C++ 大约一年了,积极使用 C++11/14。我经常在代码和库中看到 `noexcept` 关键字,但不太清楚何时真正需要应用它。
例如,我写了一个简单的文件操作包装类。通常我是这样定义方法的:
```cpp
class FileWrapper {
public:
FileWrapper(const std::string& filename) : file_(fopen(filename.c_str(), "r")) {
if (!file_) throw std::runtime_error("Cannot open file");
}
~FileWrapper() {
if (file_) fclose(file_);
}
bool is_open() const { return file_ != nullptr; }
std::string read_line() {
// ... 读取错误时可能抛出异常
}
void close() {
if (file_) { fclose(file_); file_ = nullptr; }
}
private:
FILE* file_;
};
```
问题:
1. 是否需要为析构函数标记 `noexcept`?我听说析构函数默认是 `noexcept`,但有必要显式写出吗?