断字符串异常?

时间:2016-03-30 13:08:15

标签: c++

我正在抛出一些解析异常。但是一个例外需要破解字符串..?

//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(或编译器)的问题?

1 个答案:

答案 0 :(得分:3)

As noted in the comments,如果不创建未定义的行为,则无法返回本地c_str的{​​{1}}。在异常本身上存储string值的string缓存可能是有意义的; the char* returned by what needs to live as long as the exception object,因此对异常进行缓存是合理的。

what

或者,您可以在构造函数中计算值,以使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兼容(与C ++标准库异常相匹配)。