c++异常从字符串转换为c_str创建垃圾字符

标签 c++ string exception

我有如下代码:

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:Caught in

▒g▒▒▒g▒▒EException2:Caught in

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

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

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

最佳答案

string getMyexceptionStr() { 返回 myexception; - 这会在临时 string 中返回 myexception 的拷贝。

const char* what() { 返回 getMyexceptionStr().c_str(); - 这将返回一个悬挂指针,因为临时 string; 处被销毁。

更改 getMyexceptionStr() 以返回 const string&

关于c++异常从字符串转换为c_str创建垃圾字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50795829/

相关文章:

c++ - 字节顺序转换和 g++ 警告

C# - 当应用程序使用另一种语言时获取英语异常消息?

java - 使字符串静态有什么用

c# - 使用 C# 将字符串列表写入文本文件,添加为邮件的附件

python - 使用异常返回异常值: is this good practice?

c# - 自定义中间件不处理调试运行 ASP.NET CORE 的异常

c++ - C++ 中的 std::move() 和 xvalue

c++ - 按位,位掩码 : whats wrong here?

c++ - 确保在 C++ 中调用析构函数的信号处理

java - 如何在wordcount hadoop中用逗号、空格、句点(.)、制表符(\t)、括号()、方括号[]和大括号({})字符分隔单词?