Why is this singleton behavior happening?

One of my junior programmers created a singleton, but it acts weirdly:

I know that you should not access an object like this, but the way they did it, and I can’t explain why this happens - After the call to delete the instance, I put a breakpoint on the line after and I can still access to someObject and its properties. This view makes sense as link access due to the mySingleton object, not MyInstance, ... and as you can see, I cannot explain this clearly, who can help?

eg.

    Dim x As MySingleton = MySingleton.GetInstance()

    x.someObject.int = 5
    x.someObject.str = "hello"

    Console.Out.WriteLine(x.someObject.int.ToString)
    Console.Out.WriteLine(x.someObject.str.ToString)

    MySingleton.RemoveInstance()

    Console.Out.WriteLine(x.someObject.int.ToString) //still exists!
    Console.Out.WriteLine(x.someObject.str.ToString) //still exists!

Here's the Psuedo code for singleton:

Public Class MySingleton

    Private Shared _myInstance As MySingleton

    Public someObject As New Class1

    Public Shared Function GetInstance() As MySingleton
        If _myInstance Is Nothing Then
            _myInstance = New MySingleton
        End If
        Return _myInstance

    End Function

    Public Shared Sub RemoveInstance()
        _myInstance = Nothing
    End Sub


    End Class

Personally, I do not write my singleton like this - I have an instance of the object as a separate class. but each to his own.

+3
3

, .NET / . Nothing, . , , x.

Nothing null , ; . , :

Dim anObject as new MyObject

anObject.DoAnOperation()
[1]
... 
...
'more code
...
...

Set anObject = Nothing
[2]

Nothing, [1]. , [2]. , .

:

http://msdn.microsoft.com/en-us/library/ee787088.aspx

+1

, MySingleton._myInstance .

x .

Edit:
:

:

var A = new Class();
var B = A;
A = null;
// Here B still has that reference to the created object
+6

The first line gets a link to your singleton, and that link will remain valid until the object is garbage collected. However, as long as there are references to the object, it will not collect garbage, so you will continue to reference the actual object until you explicitly assign x to another.

+4
source

Source: https://habr.com/ru/post/1774091/


All Articles