简体   繁体   English

C++ 删除/(递归)对象破坏-问题

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

I have problems understanding why the following code always throws this exception:我无法理解为什么以下代码总是抛出此异常:

AddressSanitizer: attempting double-free AddressSanitizer:尝试双重释放

I guess I'm not getting some part of the new/delete process, but just can't figure it out.我想我没有得到新/删除过程的某些部分,但就是想不通。

Thanks for any help in advance guys... ..or girls;P感谢您提前提供任何帮助......或者女孩;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;
}

Your issues is partially here:您的问题部分在这里:

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

You take argument by value, so you do copy.你通过价值来论证,所以你要复制。

Your real issue is that your classes doesn't respect rule of 3/5/0.您真正的问题是您的课程不遵守 3/5/0 规则。

So both g destructor and s destructor release the same resources.所以g析构函数和s析构函数都释放相同的资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM