[英]How to fix “terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid” exception?
I have code below that consist of binary tree data structure:我下面的代码由二叉树数据结构组成:
#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;
}
When I run it, it showed me an exeption like this below:当我运行它时,它向我显示了如下所示的异常:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Can anyone help me to fix this runtime error, please?谁能帮我解决这个运行时错误,好吗? Thanks in advance...提前致谢...
You're trying to initialize an std::string
with 0
.您正在尝试使用0
初始化std::string
。 std::string
doesn't have a ctor that takes just an int
, but it does have one that takes a pointer, and an integer literal 0
can convert implicitly to a pointer--specifically, a null pointer. std::string
没有一个只接受一个int
的 ctor,但它确实有一个接受一个指针的 ctor,并且 integer 文字0
可以隐式转换为指针 - 特别是 null 指针。
But, when you pass a pointer to initialize an std::string
, it's required to be a non-null pointer, so passing zero breaks things (and the error message you're getting is telling you that you've tried to break it).但是,当你传递一个指针来初始化一个std::string
时,它必须是一个非空指针,所以传递零会破坏事情(你得到的错误消息告诉你你试图破坏它)。
My advice would be to get rid of your: DEFAULT_NODE_VALUE
, and instead provide a default argument to value initialize the item in the node:我的建议是摆脱你的: DEFAULT_NODE_VALUE
,而是提供一个默认参数来初始化节点中的项目:
node(T a = T()):val(a){}
In which case, it'll work about as it previously did for things like node<int>
, but will also work correctly for types that can't be initialized from 0
.在这种情况下,它将像以前对node<int>
之类的东西一样工作,但对于无法从0
初始化的类型也能正常工作。 This also gets rid of the ugly DEFAULT_NODE_VALUE
in the client code.这也摆脱了客户端代码中丑陋的DEFAULT_NODE_VALUE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.