Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

vb6 - What is the reason for not instantiating an object at the time of declaration?

I had to delve into some VB6 code recently and I saw this pattern all over the place:

dim o as obj
set o = new obj

Why not this?

dim o as new obj

I remember from 15 years ago that there was a good reason for this, but I can't remember what it was now. Anyone remember? Is the reason still valid?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There may be other reasons but in VB6 using the New keyword when you Dim an object can cause unexpected results because VB will instantiate the object whenever it is referenced.

Dim objMyObject as New SomeObject

Set objMyObject = Nothing   ' the object is nothing

If objMyObject Is Nothing Then  ' referencing the object instantiates again
   MsgBox "My object is destroyed"  ' what you would probably expect
Else
   MsgBox "My object still exists"
End If

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...