小编pip*_*289的帖子

从函数返回const char*的正确方法,例如,重写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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在上面的代码中使用了一个静态分析工具,它抱怨字符串s会离开作用域并破坏与字符串相关的内存,所以如果我在某些部分使用what(),它可能会成为一个问题.我的代码.

如果有正确的方法从函数返回const char*而没有这些问题保留适当的内存管理?

c++

2
推荐指数
2
解决办法
1227
查看次数

未初始化的错误

我需要做些什么来修复程序中未初始化的错误?该程序假设打印一个数字具有的除数,但仍然显示错误,表示变量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++

0
推荐指数
1
解决办法
730
查看次数

标签 统计

c++ ×2