I'm trying to implement smart pointers in doubly linked list (university task). Before that I've done the same task in pure C with raw pointers. The problem is when I add new Node to List by addNode() more than twice I have crash (I use CodeLite(g++), Windows 10 64bit). I assume that the problem is my memory management (destructors of Node and List). But I feel I don't have enough qualification to solve that. So any help will be appreciated.
#include <stdlib.h>
#include <iostream>
#include <memory>
using namespace std;
template <typename T>
struct Node {
T Value;
weak_ptr<Node<T>> prev;
shared_ptr<Node<T>> next;
~Node() {
while (next){
prev = next->next;
next.reset();
next = prev.lock();
}
}
};
template<typename T>
class List
{public:
shared_ptr<Node<T>> start;
weak_ptr<Node<T>> end;
int size;
public:
List(): size(0){};
~List();
void addNode (T value);
};
template <typename T> List<T>::~List()
{
cout<<"List destructor"<<endl;
while (start){
auto sp = end.lock();
end = start->next;
start.reset(sp.get());
}
}
template <typename T> void List<T>::addNode(T value){
Node<T>* nd = new Node<T>;
if (size==0){
start.reset(nd);
start->Value = value;
end = start;
}
else{
auto sp = end.lock();
auto sp2 = end.lock();
sp->next.reset(nd);
sp.reset(sp->next.get());
sp->prev = sp2;
sp->Value = value;
cout<<"Value size is "<<size<<" "<<sp->Value<<endl;
end = sp;
}
size++;
return;
}
int main ()
{
system("CLS");
string a;
string b;
string c;
a = "1 test";
b = "2 test";
c = "3 test";
List<string> ls;
ls.addNode(a);
ls.addNode(b);
ls.addNode(c);
return 0;
}