当扩展std :: exception时,我想知道覆盖what()的正确方法?
可以说我有一个例外类:
class MyException : public std::exception {
public:
MyException(const string& _type) : m_type(_type) {}
virtual const char* what() const throw() {
string s = "Error::" + _type;
return s.c_str();
}
}
Run Code Online (Sandbox Code Playgroud)
我在上面的代码中使用了一个静态分析工具,它抱怨字符串s会离开作用域并破坏与字符串相关的内存,所以如果我在某些部分使用what(),它可能会成为一个问题.我的代码.
如果有正确的方法从函数返回const char*而没有这些问题保留适当的内存管理?
您需要将string实例存储在类中,否则当what()函数返回时将释放它的内存,使调用者留下悬空指针:
class MyException : public std::exception {
public:
MyException(const std::string& _type)
: m_what("Error::" + _type)
{
}
virtual const char* what() const throw() {
return m_what.c_str();
}
private:
std::string m_what;
}
Run Code Online (Sandbox Code Playgroud)
您正在返回指向临时的指针,该指针将在what()调用退出时被销毁.
从而std::runtime_error不是派生您的异常类std::exception.然后将代码更改为:
class MyException : public std::runtime_error {
public:
MyException(const string& _type)
: std::runtime_error("Error::" + _type)
{}
};
Run Code Online (Sandbox Code Playgroud)
std::runtime_error实现what()成员函数,因此您的类不需要实现它.
| 归档时间: |
|
| 查看次数: |
1227 次 |
| 最近记录: |