Does this leak memory?

Dim Public strBldr As New StringBuilder("test", 5)
‘alloc a StringBuilder
MsgBox(strBldr.ToString())	‘use the StringBuilder
strBldr =   New StringBuilder("a", 2)
‘did the destructor of StringBuilder holding “test”  
'free up its memory?

As StringBuilder does not implement a Clear() method, and I am having timing issues with the MSDN offered .Length = 0 + .Capacity = 0 solution; the following works fine if I uncomment any of the MsgBox() statements but fails to set retVal.Capacity = 2 elsewise and therefore the retVal.Append fails.

Public Function WhatChar(ByVal CBox As ComboBox, ByRef retVal As StringBuilder) As Integer
        WhatChar = CBox.SelectedIndex
        retVal.Length = 0
        retVal.Capacity = 0
        retVal.Capacity = 2
        'MsgBox("cb INDEX ")
        Select Case CBox.SelectedIndex
            Case 0  'single space
                retVal.Append(" ")
            Case 1  'hyphen
                retVal.Append("-")
            Case 2  'single space>hyphen<single space>
                retVal.Capacity = 4
                retVal.Append(" - ")
            Case 3  'open single quote
                retVal.Append("`")
            Case 4  'underscore
                retVal.Append("_")
            Case Else   'everything else
                retVal.Append(CBox.SelectedText)
        End Select
        'MsgBox("retVal " + retVal.ToString())
    End Function

The forum at MSDN has conflicting information. Any thoughts?

Well.... I don't see when the destructor would be called.... that is, does a second new mean a call to the first destructor? I don't think so... because destruction happens when the object is set to nothing, or it goes out of scope... and neither one is happening. You are simply assigning the object variable to a new instance of an object... and the first object is not set to nothing, nor is it going out of scope... If the idea though, that when the object no longer has the variable pointing to it that it gets destructed can be tested...so I did a for loop from 0 to 1000, and basically just put in it strBldr = New StringBuilder("a", 2).. If the destructor gets called when strBldr no longer points to it, then the application shouldn't consume more memory (maybe temporarily while it's swapping stuff around, but not permanently). Then I opened up Windows Task Manager, and sorted the list by memory usage. Then I clicked the button with the for loop in it, a few times... and sure enough, the memory usage of the EXE kept growing more and more each time I did it. (I made the initial strBldr variable public, in the class scope... so it was declared at the top :) ) So to answer your question.... probably.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.