Template list

Write your question here.
Hello, I'm doing a homework aasignment on templates, and i have to build a list.
The problem starts when i am trying to add elements to the list. For instance if i chose to add 5 different elements (1,2,3,4,5) the output will be (5,5,5,5,5).
I have no idea how to fix it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  void add_back(T t){
		Node* tmp = new Node;
		tmp -> m_data = &t;
		if(m_head ==  NULL)
		{

			m_head = tmp;
			m_tail = m_head;
			m_size += 1;
		}
		else
		{
			m_tail -> m_next = tmp;
			tmp -> m_prev = m_tail;
			m_tail = tmp;
			m_size += 1;
		}
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	 void add_front(T t){
		Node* tmp = new Node;
		tmp -> m_data = &t;
		if(m_head ==  NULL)
		{
			m_head = tmp;
			m_size += 1;
		}
		else
		{
			m_head -> m_prev = tmp;
			tmp -> m_next = m_head;
			m_head = tmp;
			m_size += 1;
		}
	 }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
	List<int> list;

	if(!list.isEmpty()) 
		cout<<"Error"<<endl;
	list.add_back(5);
	list.add_back(21);
	list.add_back(34);
	list.add_front(70);
	cout<<list.size()<<endl; //size is 1
	if(list.isEmpty()) 
		cout<<"Error"<<endl;
	cout<<list.pop_back()<<endl;
	if(!list.isEmpty()) 
		cout<<"Error"<<endl;
}
tmp -> m_data = &t;

You must understand that in your code, t is basically a local variable (a value copy of the original parameter that was passed).

As soon as the add_front() / add_back() function ends, t "dies" and the memory address of t which you're storing in tmp->m_data becomes invalid.

Also, even though you haven't posted the complete code, I feel the need to remind you that C++ is not a garbage-collected language; this means that every new must have its corresponding delete otherwise a memory leak may occur. You did delete your new'd memory, didn't you?

Finally your algorithm is a bit strange, are you sure you're supposed to be working on a doubly-linked list, and also keep track of the "tail"?
ok i understand, but what can i do, to not lose the data? void add_front(T& t){ will help, or i need to do something else?
Simply store a copy, instead of a memory address in a pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T>
struct Node
{
    T data;
};

// ...

void add_front(T t)
{
    Node *tmp = new Node;

    tmp->data = t;

    // ...
}


void add_front(T& t)
This passes t by reference, and is probably not what you want. The & when put between a variable name and its type means "reference" just as an * between a variable and its type means "pointer". It is not the & (address-of) operator that you've been using so far. So don't do this.
Topic archived. No new replies allowed.