c++ - 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
解决方案
string getMyexceptionStr() { return myexception; }
- 这将返回myexception
一个临时 string
的.
const char* what() { return getMyexceptionStr().c_str(); }
- 这将返回一个悬空指针,因为临时string
对象在;
.
改为getMyexceptionStr()
返回const string&
。
推荐阅读
- postgresql - Postgres:大块的快速切面
- swift - Swift Firebase 首先写得非常慢
- javascript - 多个文件 Vue js 设置——[Vue 警告]:v-on 处理程序中的错误:“TypeError:formSubmitMessage 不是函数”
- twilio - Twilio 国际短信未发送
- vba - 如何对具有指定 ExchangeStoreType 的帐户运行规则?
- vhdl - 我不知道在 VHDL 测试台的时间间隔上写什么
- python - 如何使用内置的 round() 函数
- ios - SKStoreReviewController.requestReview(在:场景中)iOS 14 在 Appstore 中不起作用
- generics - 如何实现具有特征 MyTrait 的结构?
- python - 创建具有不同类的 MNIST 格式的数据集?