【问题标题】:terminate called after throwing an instance of 'std::logic_error' basic_string::_S_construct null not valid在抛出 'std::logic_error' basic_string::_S_construct null 的实例后调用终止无效
【发布时间】:2017-12-13 03:02:24
【问题描述】:
string Solution::findDigitsInBinary(int A) {
    int i, j, rem;

    if(A == 0) {
        return 0;
    }
    else {
        string res="";

        while(A > 0) {
            rem = A % 2;
            res = res + to_string(rem);
            A = A / 2;
        }

        return std::string(res.rbegin(), res.rend());
    }
}

如何解决这个问题

【问题讨论】:

    标签: c++ string exception


    【解决方案1】:

    引起的问题:

    if(A == 0) {
        return 0;
    }
    

    当A == 0 它尝试从0 到construct an std::string。这是相等的——因为隐式构造函数调用——到:

    return std::string(0);
    

    在这种情况下,0 表示一个非法的 空指针。错误信息

    basic_string::_M_construct null 无效

    意思完全一样。

    如果您希望在A == 0 时返回零,可以通过将return 0 更改为:

    return "0";
    

    【讨论】:

    • 我对否决票很好奇。否决者是否在我的回答中发现了一个严重的问题,无法建议在 cmets 中进行编辑?
    【解决方案2】:

    return 0; 调用隐式字符串构造函数,接受指向 char return std::string(const char *(0)) 的指针。该指针不允许为空。要返回一个空字符串,写return std::string();

    【讨论】:

      【解决方案3】:

      由于该方法预计会返回 std::string,因此如果 A == 0 是 true,您将返回 std::string(0) ~ std::string(NULL)。

      返回 std::string 的默认值 - 我猜 - 只需 return std::string(); 而不是 return 0;。

      【讨论】:

        猜你喜欢
        • 2017-04-11
        • 1970-01-01
        • 2019-02-08
        • 2012-07-27
        • 2021-12-16
        • 2023-01-17
        • 2022-01-11
        • 2019-10-26
        • 1970-01-01
        相关资源
        最近更新 更多