Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Visual Basic has class references which are the same as C++. But is that reference equivalent to a C++ pointer (fixed location) or a C++ Handle (managed code - relocatable)?

What I have tried:

VB
dim myclassallocation as NEW myclass
dim myclassreference as myclass
Posted
Updated 29-Aug-23 2:21am
v2

1 solution

In Visual Basic, when you create a class reference using the Dim statement with the New keyword, it is equivalent to a handle to a managed object, similar to C++ handles. The reference can be relocated in memory due to garbage collection and other memory management processes.

Your myclassallocation is a variable that holds an instance of your MyClass class. The New keyword indicates that you want to create a new instance of the class. In this case, memory is allocated for the object, and the reference is stored in the myclassallocation variable.

Your myclassreference is declared as a reference to an instance of your MyClass class. It does not hold an actual instance, it's just a reference that can be assigned to point to an instance later on.

Both myclassallocation and myclassreference would behave the same. They are references to managed objects, and the garbage collector will take care of relocating them as needed.

C++ pointers are closer to raw memory addresses, and they can be used to point to both managed and unmanaged memory, but also require manual memory management and are not automatically relocated like managed references in VB.

As a small example, you can use:
VB.NET
Public Class MyClass
    Public Sub New()
        Console.WriteLine("MyClass instance was created.")
    End Sub
End Class

Module MainModule
    Sub Main()
        Dim myclassallocation As New MyClass
        Dim myclassreference As MyClass

        'Assign the reference to the instance created above...
        myclassreference = myclassallocation

        'Without using myclassallocation directly...
        
        'At this point, myclassallocation and myclassreference 
        'both point to the same instance where
        'the object will be managed by the garbage collector...

        'Nullify the reference to release the instance 
        'for garbage collection...
        myclassreference = Nothing

        'Force a garbage collection to clean up unreferenced objects...
        GC.Collect()

        'The Finalize method of MyClass will be called here 
        'as part of garbage collection...

        'Wait for user input before exiting...
        Console.ReadLine()
    End Sub
End Module
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900