【问题标题】:std::logic_error: basic_string::_s_construct null not validstd::logic_error: basic_string::_s_construct null 无效
【发布时间】:2015-03-14 21:19:49
【问题描述】:

我在这个程序中收到std::logic_error: basic_string::_s_construct null not valid。我该如何解决?我已经尝试过previously posted solution,但我自己无法更正。

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
     stack<string> s;
     string temp, exp[] = "abc-+de-fg-h+/*";
     string ch1 = 0, ch2 = 0, ch = 0;
     int sizeExp = sizeof(exp)/sizeof(*exp);
     for(int i=0; i < sizeExp ; i++) {
         ch = exp[i];
         if (ch == "*" || ch == "/" || ch == "+" || ch == "-") {
             if (s.empty() && sizeof(temp) != sizeof(exp)) {
                 cout << "Error in Expression." << endl;
             }
             else {
                 if (sizeof(s.top()) != sizeof(char)){
                     ch1 = s.top();
                     s.pop();
                     ch2 = s.top();
                     temp = '(' + ch2 + ')' + exp[i] + '(' + ch1 + ')';
                     s.push(temp);
                 }
                 else {
                     ch1 = s.top();
                     s.pop();
                     ch2 = s.top();
                     temp = ch2 + exp[i] + ch1;
                     s.push(temp);
                 }
             }
         }
         else {
             s.push(exp[i]);
         }
     }
     cout << temp << endl << "Is your Infix Expression for ";
     cout << exp;
     return 0;
}

【问题讨论】:

标签: c++


【解决方案1】:

问题在于std::string str = 0; 之类的语句。这会导致未定义的行为。使用std::string str = ""; 创建空字符串。

std::string str = 0; 解析为 constructor std::string::string(const char* s, const Allocator&amp; alloc = Allocator())。当snullptr 时,此构造函数的行为未定义。您的0 参数被转换为nullptr

【讨论】:

    【解决方案2】:

    std::string 的文档明确指出您不应从空指针构造一个。然而,你在这里,就是这样做的!

    string ch1 = 0, ch2 = 0, ch = 0;  // BAD
    string ch1, ch2, c;               // Substantially better
    

    【讨论】:

    • 公平地说,string ch1 = 0; 的含义对于初学者来说可能并不明显。实际上,这甚至可以编译的事实可以很好地被认为是该语言的缺陷。要是nullptr一直都在就好了……:)
    猜你喜欢
    • 2021-12-16
    • 2017-12-13
    • 2017-04-11
    • 1970-01-01
    • 2012-07-27
    • 2019-02-08
    • 1970-01-01
    • 2019-06-23
    • 2022-01-11
    相关资源
    最近更新 更多