smart pointer linked list - leak free?

May 15, 2019 at 7:23pm
I'm new to templates and smart pointers, I'm wondering if the below is pretty much a leak free implementation? Obviously it lacks functionality, and i'm assuming to remove an element you just change the previous next pointer to the one after it, and the memory will be auto freed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//node.hpp

#include <memory>

template <typename T>
class node {
public:
	std::unique_ptr<T> data;
	std::shared_ptr<node> next;
	bool operator = (std::shared_ptr<node<T>> n)
	{
		this->next = n;
	}
};

//list.hpp

#include "node.h"
#include <ostream>
#include <iostream>

template <typename T>
class jlist {
private:
	std::shared_ptr<node<T>> head{ nullptr };
public:
	jlist() = default;
	~jlist() = default;
	void add(T item)
	{
		if (head == nullptr)
		{
			head = std::make_shared<node<T>>();
			head->data = std::make_unique<T>(item);
			head->next = nullptr;
		}
		else
		{
			std::shared_ptr<node<T>> iter = head;
			while (iter->next != nullptr)
			{
				iter = iter->next;
			}
			std::shared_ptr<node<T>> temp =     std::make_shared<node<T>>();
			temp->data = std::make_unique<T>(item);
			iter->next = temp;
		}
	}
	void print()
	{
		if (head == nullptr)
			return;
		std::shared_ptr<node<T>> iter = head;
		std::cout << *iter->data << std::endl;
		while (iter->next != nullptr)
		{
			iter = iter->next;
			std::cout << *iter->data << std::endl;
		}
	}
	friend std::ostream& operator << (const std::ostream& os, const T& item)
	{
		return os << item;
	}
};
May 15, 2019 at 7:35pm
This doesn’t answer your question, but just as an aside note, if your compiler already support std::observer_ptr
https://en.cppreference.com/w/cpp/experimental/observer_ptr
you could try to use it in place of std::shared_ptr (all nodes should anyway be managed by a unique_ptr, shouldn’t they?).
May 16, 2019 at 12:26am
thanks bro
May 16, 2019 at 1:40am
Your initial theory is correct.

If you delete the first node, that will subsequently delete and free the memory of all other nodes in the list.

Also, if you reorient the next/prev pointers (prev would be in a double linked list), then yes, the object previous referenced will be freed.

No leaks.

Topic archived. No new replies allowed.