[英]Proper method of returning const char* from a function, e.g., overriding std::exception::what()
When extending std::exception, I am wondering the proper way of overriding what()? 当扩展std :: exception时,我想知道覆盖what()的正确方法?
Lets say I have an exception class : 可以说我有一个例外类:
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();
}
}
I have used a static analysis tool on the above code, and it is complaining that the string s will leave the scope and destroy the memory associated with the string, so it could potentially be a problem if I use what() in some part of my code. 我在上面的代码中使用了一个静态分析工具,它抱怨字符串s会离开作用域并破坏与字符串相关的内存,所以如果我在某些部分使用what(),它可能会成为一个问题。我的代码。
If there a proper way of returning a const char* from a function without these issues retaining proper memory management? 如果有正确的方法从函数返回const char *而没有这些问题保留适当的内存管理?
You need to store the string
instance inside your class, otherwise the memory for it will be freed when your what()
function returns, leaving the caller with a dangling pointer: 你需要在你的类中存储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;
}
You are returning a pointer to a temporary that will be destroyed when the what()
call exits. 您正在返回一个指向临时的指针,当what()
调用退出时将被销毁。
Derive your exception class from std::runtime_error
instead of std::exception
. 从std::runtime_error
而不是std::exception
派生您的异常类。 Then change the code to: 然后将代码更改为:
class MyException : public std::runtime_error {
public:
MyException(const string& _type)
: std::runtime_error("Error::" + _type)
{}
};
std::runtime_error
implements the what()
member function, so there's no need for your class to implement it. std::runtime_error
实现了what()
成员函数,因此您的类不需要实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.