C++ 异常从字符串转换为c_str会创建垃圾字符
c++ exception convert from string to c_str creates Junk chars
我有如下代码:
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&
。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 超级级别的方法称为super具有sub的str attr 实例在循环 实例中创建的方法是作为super的指针存储在向