C++删除/(递归)对象销毁问题



我无法理解为什么以下代码总是抛出此异常:

地址消毒剂:尝试双免

我想我没有获得新/删除过程的某些部分,但只是无法弄清楚。

提前感谢您的任何帮助...或女孩;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析构函数释放相同的资源。

最新更新