Chezi
Chezi

Reputation: 63

Disposing a vb6 object - A surprising problem

I have "invented" a linked-list technique in vb6 by placing a pointer inside the object:

Class FooBar:
Public ptr As FooBar

Now I just hold a pointer to the head of the list, inside Head.ptr points to the next object, Head.ptr.ptr points to the next object, etc.

When I want to destroy the list I just use Set Head = Nothing, this result in clearing Head.ptr, which in turn triggers clearing Head.ptr.ptr etc, resulting in an empty list (I actually checked it by placing a break-point in the Class_Terminate event).

This works nice and neat, until I have like 10,000 objects in the list. Now the line Set Head = Nothing results in "Out of stack memory" error, after which an IDE crash.

Turns out, vb6 is clearing the object recursively (it happens even if I don't have the Class_Terminate event).

So I thought I should destroy the list "manually", with some sort of loop. but I couldn't figure out a way to do so, as using a pointer in the loop and setting it to Nothing does... nothing since it AddRef to the object!

What should I do???

Upvotes: 0

Views: 540

Answers (2)

Chezi
Chezi

Reputation: 63

I Finally worked out a way to manually destroy the list.

A somewhat tricky but working solution.

I first add a small method to the class that clears the internal pointer without removing the object.

Class FooBar:
Public ptr As FooBar

Public Function SafeRemove() As FooBar
Set SafeRemove = ptr
Set ptr = Nothing
End Function

In a module:

Sub ClearList()
While Head Is Nothing = False
    Set Head = Head.SafeRemove
Wend
End Sub

Upvotes: 1

Mark Bertenshaw
Mark Bertenshaw

Reputation: 5689

I can understand why you get a stack overflow. You are implicitly calling the Release() method of the IUnknown interface, which them calls an internal VB destroy method, which clears down all internal state, including the variable which points to the next item, which then calls Release(), etc., etc.

To get around the stack overflow problem, you would be better off implementing a doubly linked list, and always saving a pointer to the end of the list. But then you would now have the problem of circular references, and nothing would clear down unless you had a specific disposal method.

You might as well use the VBA.Collection object, which I have been told (in the book Hardcore Visual Basic is a doubly linked list internally).

Upvotes: 0

Related Questions