![](/img/trans.png)
[英]Where in the standard is the grammar for the template argument in, e.g., `std::function<int(char)>` defined?
[英]Proper method of returning const char* from a function, e.g., overriding std::exception::what()
當擴展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();
}
}
我在上面的代碼中使用了一個靜態分析工具,它抱怨字符串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;
}
您正在返回一個指向臨時的指針,當what()
調用退出時將被銷毀。
從std::runtime_error
而不是std::exception
派生您的異常類。 然后將代碼更改為:
class MyException : public std::runtime_error {
public:
MyException(const string& _type)
: std::runtime_error("Error::" + _type)
{}
};
std::runtime_error
實現了what()
成員函數,因此您的類不需要實現它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.