c++ - 断线异常?

标签 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(或Compiler)的问题?

最佳答案

As noted in the comments ,如果不创建未定义的行为,则不能返回本地 stringc_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/

相关文章:

c++ - 只实现拷贝构造函数,不实现赋值构造函数

C++系统函数挂起应用程序

c++ - 有没有解决 nullptr_t 和指针重载之间歧义的好方法?

c++ - 对 char* 的平等测试 std::string,operator==() 总是安全的吗?

c++ - 通过引用返回/传递动态分配的对象

c++ - 去除轮廓缺陷[OpenCV]

C++ OpenGL 段错误(核心转储)运行时错误

javascript - 如何将 std::function 绑定(bind)到 JavaScript V8?

c++ - 将一个 int 传递给一个函数,然后使用该 int 创建一个数组

c++ - this[0] 在 C++ 中安全吗?