Delete Generic Pointer T

I have run into a funny problem that has me baffled. I've been throwing together a LinkedList implementation. Not really having any experience with deconstructors I've decided to give them a go. (I've grown too accustomed to Java's cushy and nice garbage collector!)

When I play out my deconstructor in my head and walk through it using the debugger it works fine until it hits this code within the node class:

1
2
3
4
5
6
7
8
template<class T>
Node<T>::~Node(void)
{
	//Clean up.
	delete element;
	
	//The next node may still be needed so don't delete it.
}


(I realized after the fact that I could have much more easily just used a struct for the nodes, however I still want to know why this doesn't work.)

Each node holds a pointer to an element of type T and a pointer to the next linked node.

In my trials the generic type T is of type string. When I use the debugger and step through the code (or just run the code), it crashes as soon as it tries to execute the code delete element;

It then displays this window:

http://screencast.com/t/ZmJmZDFhNWQt

Or if you wish not to go to the link, it says:

Debug Assertion Failed!
...some file location...
Expression:_BLOCK_TYPE_IS_VALID(PHead->nBlockUse)


When I attempt to debug the code it directs me to some crazy source code that I haven't a clue what it means.

Keeping in mind in my trials type T is string.

Thanks for any help/thoughts!
You're certainly allowed to delete pointers to template classes. Perhaps you've given it a pointer to an object that wasn't allocated on the heap?
Ah you are a genius! Totally overlooked that! The strings I had added to the LinkedList to test it were made via automatic objects. Switched 'em to be made using the new operator and it ran perfect.

Only question now is, how do I deal with non-heap allocated objects being added to the list? I know I don't have to worry about deleting them but since I DO want to delete dynamic objects I seem to be in a rut.
You can't. You just have to put a comment or something saying "don't pass automatic objects".
Reguba wrote:
Only question now is, how do I deal with non-heap allocated objects being added to the list?

You could always copy them to a string you allocate yourself:
1
2
3
4
5
6
template<class T>
Node<T>::set_value(const T& t)
{
    element = new T;
    (*element) = t;
}

However it may be worth thinking about not using pointers at all. If the user wants to use pointers then they can declare your list to be of type pointer:
 
LinkedList<std::string*> list;
Last edited on
Topic archived. No new replies allowed.