I'm trying to implement a linked list with smart pointers, to get used to using them. However I really can't wrap my head around how to handle them in constructors and assignment operators, I get lots of weird errors and I don't even know how to google them, so I thought asking here would be the simplest.
Here is my generic Link class in its current form, how it seems logical to me. The default constructor does not work, and I don't understand why. Can you show me whats the correct and elegant way to make a class that uses shared pointers?
template<class T>
class Link {
public:
template<typename> friend class LinkedList;
Link() :next(make_shared<Link<T>>), prev(make_shared<Link<T>>), val(0) {}
Link(const T& data) :next(make_shared<Link<T>>), prev(make_shared<Link<T>>), T(data) {}
Link(const Link<T>& other) :val(other.val),
next(make_shared<Link<T>>(other.next)),
prev(make_shared<Link<T>>(other.prev)) {}
Link(Link<T>&& other) :val(move(other.val)),
next(move(other.next)),
prev(move(other.prev)) {}
Link<T>& operator=(const Link<T>& other) {
val = other.val;
next = other.next;
prev = other.prev;
return *this;
}
Link<T>& operator=(Link<T>&& other) {
next = make_shared<Link<T>>(std::move(other.next));
prev = make_shared<Link<T>>(std::move(other.prev));
val = std::move(other.val);
return *this;
}
~Link() {
cout << val << " destroyed" << endl;
};
private:
shared_ptr<Link<T>> next;
shared_ptr<Link<T>> prev;
T val;
};
Aucun commentaire:
Enregistrer un commentaire