【问题标题】:How to fix "terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid" exception?如何修复“在抛出 'std::logic_error'what() 实例后调用终止:basic_string::_M_construct null not valid”异常?
【发布时间】:2021-04-04 11:04:36
【问题描述】:

下面的代码由二叉树数据结构组成:

#include <bits/stdc++.h>
#define DEFAULT_NODE_VALUE 0
using namespace std;

template <class T>
class node{
public:
    T val;
    node* right = 0;
    node* left = 0;
    node(T a):val(a){}

};

template <class T>
class tree{
public:
    node<T>* root = new node<T>(DEFAULT_NODE_VALUE);
    tree(T inp_val){
        root->val = inp_val; 
    }

    void inorder_traverse(node<T>* temp){
        if (!temp)
            return;
        inorder_traverse(temp->left);
        cout << temp->val << " -> ";
        inorder_traverse(temp->right);
    }
    void inorder_traverse(){
        inorder_traverse(root);
    }
    
};

int main()
{   
    tree<string> my_tree("mantap");
    my_tree.root->right = new node<string>("ok");
    my_tree.root->left = new node<string>("haha");

    my_tree.inorder_traverse();

    return 0;
}

当我运行它时,它向我显示了如下所示的异常:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid

谁能帮我解决这个运行时错误,好吗?提前谢谢...

【问题讨论】:

  • 首先,永远不要垃圾邮件无关的语言标签(如您拥有的 C 语言标签)。其次,don't include &lt;bits/stdc++.h&gt;。三是找some good C++ books好好学习,最好上几节课。这应该告诉你为什么你的DEFAULT_NODE_VALUE 不能适用于所有事情(或者为什么它不是真正需要的)。
  • 当构造函数tree::tree(T inp_val)root提供值时,为什么还要DEFAULT_NODE_VALUE
  • 您指定了错误的默认值 std::string,而是使用此语法 node&lt;T&gt;* root = new node&lt;T&gt;(T{});

标签: c++ exception runtime-error runtime


【解决方案1】:

您正在尝试使用0 初始化std::stringstd::string 没有一个只接受 int 的 ctor,但它确实有一个接受指针的 ctor,并且整数文字 0 可以隐式转换为指针——特别是空指针。

但是,当你传递一个指针来初始化一个 std::string 时,它必须是一个非空指针,所以传递零会破坏事情(你得到的错误消息是告诉你你试图打破它)。

我的建议是去掉你的:DEFAULT_NODE_VALUE,而是提供一个默认参数来初始化节点中的项目:

node(T a = T()):val(a){}

在这种情况下,它将像以前对 node&lt;int&gt; 之类的东西一样工作,但对于无法从 0 初始化的类型也能正常工作。这也摆脱了客户端代码中丑陋的DEFAULT_NODE_VALUE

【讨论】:

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