Gui*_*oie 12 c++ exception std c++11 clang-tidy
经过12年的中断,回到C++开发.我正在使用JetBrains的CLion软件,因为它提供了很多关于我的课程设计可能出现的问题的输入.我在我的类'constructor throw语句中得到的警告之一是:Thrown exception type is not nothrow copy constructible.以下是生成此警告的代码示例:
#include <exception>
#include <iostream>
using std::invalid_argument;
using std::string;
class MyClass {
public:
explicit MyClass(string value) throw (invalid_argument);
private:
string value;
};
MyClass::MyClass(string value) throw (invalid_argument) {
if (value.length() == 0) {
throw invalid_argument("YOLO!"); // Warning is here.
}
this->value = value;
}
Run Code Online (Sandbox Code Playgroud)
这段代码编译,我能够对它进行单元测试.但是我非常希望摆脱这个警告(为了理解我做错了什么,即使它编译了).
谢谢
尼尔提供的评论是有效的。在 C++ 11 中,throw在函数签名中使用已被弃用,而支持noexcept. 在这种情况下,我的构造函数的签名应该是:
explicit MyClass(string value) noexcept(false);
Run Code Online (Sandbox Code Playgroud)
但是,由于noexcept(false)默认情况下应用于所有函数,除非指定noexcept或noexcept(true)指定,我可以简单地使用:
explicit MyClass(string value);
Run Code Online (Sandbox Code Playgroud)
回到如何修复“抛出的异常类型不是不可抛出的复制构造”警告,我发现这篇文章很好地解释了问题是什么以及如何修复它。