When extending std::exception, I am wondering the proper way of overriding 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.
If there a proper way of returning a const char* from a function without these issues retaining proper memory management?
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:
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.
Derive your exception class from std::runtime_error
instead of 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.