我有如下代码:
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/