我正在抛出一些解析异常。但是异常需要破损的字符串..?
//Parse exception
class ParseException : public exception {
public:
//Constructor
//Arguments:
// Str: Message
// Pos: Position
ParseException(string Str, int Pos) {
msg = Str;
pos = Pos;
}
//Get what happened(From exception)
//Returns:
// Message with position
virtual const char* what() const throw() {
string str = msg;
str += " at " + to_string(pos);
return str.c_str();
}
private:
string msg; //Message
int pos; //Position
};
这是异常类。我像这样抛出这个异常:
throw ParseException("Mismatched bracket", P.Pos);
抛出此异常并转到:
try {
Parse(p);
}
catch (ParseException e) { // <<< Here
cerr << "ParseException: " << e.what() << endl;
}
我得到的是:
ParseException: ▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌
我的代码有问题吗?还是Visual Studio(或Compiler)的问题?
最佳答案
As noted in the comments ,如果不创建未定义的行为,则不能返回本地 string
的 c_str
。将 what
值的 string
缓存存储在异常本身上可能是有意义的; the char*
returned by what
needs to live as long as the exception object ,所以缓存异常是合理的。
class ParseException : public exception {
public:
//Constructor
//Arguments:
// Str: Message
// Pos: Position
ParseException(string Str, int Pos) : msg(std::move(Str)), pos(Pos) {}
//Get what happened(From exception)
//Returns:
// Message with position
virtual const char* what() const throw() {
// Lazily populate what so it's not populated until called
if (_what.empty()) {
_what = msg + " at " + to_string(pos);
}
return _what.c_str();
}
private:
string msg; //Message
int pos; //Position
string _what;
};
或者,您可以在构造函数中计算值,这样 what
保持 nothrow
兼容(匹配 C++ 标准库异常)。
关于c++ - 断线异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309816/