当扩展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*而没有这些问题保留适当的内存管理?
我需要做些什么来修复程序中未初始化的错误?该程序假设打印一个数字具有的除数,但仍然显示错误,表示变量c未初始化.
/*
/ Name: Ralph Lee Stone
/ Date: 10/10/2013
/ Project: RLStone3_HW_08
/ Description: This program gets a positive value and determines the number of divisors it has.
*/
#include <iostream>
using namespace std;
int DivisorCount(int x)
{
int counter = 0;
for(int c; x < c; c++)
{
if (x%c==0)
counter++;
}
return counter;
}
int main()
{
int x;
cout << "Please a positive value: ";
cin >> x;
cout << x << "has this many divsors: …Run Code Online (Sandbox Code Playgroud) c++ ×2