首页 > 解决方案 > c++ 异常从字符串转换为 c_str 创建垃圾字符

问题描述

我有如下代码:

class BaseException : public std::exception {
 private:
  string myexception;

   public:
  BaseException(string str):myexception(str){}
   virtual const char* what() const throw()  { return myexception.c_str();}

  string getMyexceptionStr() { return myexception};
  }

  class CustomException1 : public std::exception {
   public:
  CustomException1(string str):BaseException("CustomException1:"+str){}
   virtual const char* what() const throw()  { return getMyexceptionStr().c_str();}
  }

  class CustomException2 : public std::exception {
   public:
  CustomException2(string str):BaseException("CustomException2:" + str){}
   virtual const char* what() const throw()  { return getMyexceptionStr().c_str();}
  }


    void TestException1(){
    throw CustomException2("Caught in ");
  }

  void TestException2(){
    throw CustomException2("Caught in ");
  }

  int main(){

  try{
  TestException1();
  }
  catch(BaseException &e){
  cout << e.what();
  }

    try{
  TestException2();
  }
  catch(BaseException &e){
  cout << e.what();
  }

  }

每当我运行这个时,我都会得到下面的代码

▒g▒▒▒g▒▒Exception1:陷入

▒g▒▒▒g▒▒EException2:陷入

我在同一个类上下文中返回成员变量,范围应该存在,但我仍然得到垃圾字符。

为了避免垃圾字符,最好的处理方法是什么?

由于某些限制,我在返回异常时不能使用 malloc 或 strdup

标签: c++stringexception

解决方案


string getMyexceptionStr() { return myexception; }- 这将返回myexception一个临时 string的.

const char* what() { return getMyexceptionStr().c_str(); }- 这将返回一个悬空指针,因为临时string对象在;.

改为getMyexceptionStr()返回const string&


推荐阅读