簡體   English   中英

如何修復“在拋出 'std::logic_error'what(): basic_string::_M_construct null 無效的實例后調用終止”異常?

[英]How to fix “terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid” exception?

我下面的代碼由二叉樹數據結構組成:

#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

誰能幫我解決這個運行時錯誤,好嗎? 提前致謝...

您正在嘗試使用0初始化std::string std::string沒有一個只接受一個int的 ctor,但它確實有一個接受一個指針的 ctor,並且 integer 文字0可以隱式轉換為指針 - 特別是 null 指針。

但是,當你傳遞一個指針來初始化一個std::string時,它必須是一個非空指針,所以傳遞零會破壞事情(你得到的錯誤消息告訴你你試圖破壞它)。

我的建議是擺脫你的: DEFAULT_NODE_VALUE ,而是提供一個默認參數來初始化節點中的項目:

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

在這種情況下,它將像以前對node<int>之類的東西一樣工作,但對於無法從0初始化的類型也能正常工作。 這也擺脫了客戶端代碼中丑陋的DEFAULT_NODE_VALUE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM