C++ 中更松散的抛出说明符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22698653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looser Throw Specifier in C++
提问by user2824889
What does this error mean? How can I fix it? This is the header code that's causing it:
这个错误是什么意思?我该如何解决?这是导致它的标题代码:
class BadJumbleException : public exception {
public:
BadJumbleException (const string& msg); // Constructor, accepts a string as the message
string& what(); // Returns the message string
private:
string message; // Stores the exception message
};
And this is the source code:
这是源代码:
BadJumbleException::BadJumbleException (const string& m) : message(m) {}
string& BadJumbleException::what() { return message; }
EDIT: This is the error:
编辑:这是错误:
looser throw specifier for 'virtual BadJumbleException::~BadJumbleException()
'virtual BadJumbleException::~BadJumbleException() 的更宽松的抛出说明符
回答by Lightness Races in Orbit
In C++03, per §18.6.1/5, std::exception
has a destructor that is declared such that no exceptions can be thrown out of it (a compilation error will be caused instead).
在 C++03 中,根据 §18.6.1/5,std::exception
有一个析构函数被声明为不会抛出异常(反而会导致编译错误)。
The language requires that when you derive from such a type, your own destructor must have the same restriction:
该语言要求当您从此类类型派生时,您自己的析构函数必须具有相同的限制:
virtual BadJumbleException::~BadJumbleException() throw() {}
// ^^^^^^^
This is because an overriding function may not have a looser throw specification.
这是因为覆盖函数可能没有更宽松的 throw 规范。
In C++11, std::exception::~exception
is notmarked throw()
(or noexcept
) explicitly in the library code, but all destructors are noexcept(true)
by default.
在C ++ 11,std::exception::~exception
被未标记throw()
(或noexcept
)明确地在库中的代码,但是所有析构函数是noexcept(true)
默认情况下。
Since that rule would include yourdestructor and allow your program to compile, this leads me to conclude that you are not reallycompiling as C++11.
由于该规则将包括您的析构函数并允许您的程序进行编译,这使我得出结论,您并没有真正按照 C++11 进行编译。
回答by Mital Vora
I was getting similar exception for one of my sample code. I tried to implement this in c++14. Here is the implementation:
我的示例代码之一遇到了类似的异常。我试图在 c++14 中实现这一点。这是实现:
class BadJumbleException : public std::exception {
public:
BadJumbleException(const std::string& m_) : msg(m_) {}
virtual ~BadJumbleException() {}
virtual const char * what() const throw() {
return msg.c_str();
}
private:
const std::string msg;
};