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

c++ exception convert from string to c_str creates Junk chars

本文关键字:str 创建 字符 异常 字符串 转换 C++      更新时间:2023-10-16

我有如下代码:

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▒▒异常1:陷入

▒g▒▒▒▒▒EException2:陷入困境

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

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

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

string getMyexceptionStr() { return myexception; }- 这会在临时string中返回myexception的副本。

const char* what() { return getMyexceptionStr().c_str(); }- 这将返回一个悬空指针,因为临时string;处被破坏。

改为将getMyexceptionStr()更改为返回const string&