簡體   English   中英

C++ 刪除/(遞歸)對象破壞-問題

[英]C++ deleting/(recursive) Object-Destruction -issues

我無法理解為什么以下代碼總是拋出此異常:

AddressSanitizer:嘗試雙重釋放

我想我沒有得到新/刪除過程的某些部分,但就是想不通。

感謝您提前提供任何幫助......或者女孩;P

#include <iostream>
using namespace std;

template <typename Key, size_t N >
class TSet {
    struct Thing; using Link = Thing *;
    struct Thing{
        Key key;
        Link link{nullptr};
        ~Thing(){ if (link){ delete[] link; link=nullptr; }}
    };
    Link root{nullptr};
    size_t size;

    void    addB_Sub(Link e){ 
        if ( e->link ) { addB_Sub(e->link); }
        else e->link= new Thing[N];
    }
public:
    TSet(): root{new Thing[N]}, size{N} {}
    ~TSet(){  delete[] root; }//if (root)

    void    addB(const size_t &i){ addB_Sub(root+i); }

std::ostream &show(std::ostream &o) {
        if (!(root)) return o;
        Link peak;
        size_t count;
        for (size_t i{size}; i--; ) { cout<<'['<<i<<']';
            count=0;
            peak=(root+i);
            while (peak->link) { ++count; peak=peak->link; }
            o<<count<<", ";
        }
        cout<<"end";
        peak=nullptr;
        return o;
    }
};
template <typename Key, size_t N>
std::ostream &operator<<(ostream& o,TSet<Key, N> g){ return g.show(o); } 

int main(){
    TSet<int,5> s;
    for (int i{7}; i>0; --i) s.addB(1);
    for (int i{4}; i>0; --i) s.addB(3);
    for (int i{2}; i>0; --i) s.addB(4);
    cout<<s<<endl;
}

您的問題部分在這里:

template <typename Key, size_t N>
std::ostream &operator<<(ostream& o, TSet<Key, N> g);

你通過價值來論證,所以你要復制。

您真正的問題是您的課程不遵守 3/5/0 規則。

所以g析構函數和s析構函數都釋放相同的資源。

暫無
暫無

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

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