I'm very interested in languages and their underpinnings, and I'd like to pose this question to the community. Are the following analagous to eachother in these languages?
C#
Foo bar = default(Foo); //alloc开发者_如何学C
bar = new Foo(); //init
VB.NET
Dim bar As Foo = Nothing 'alloc
bar = New Foo() 'init
Objective-C
Foo* bar = [Foo alloc]; //alloc
bar = [bar init]; //init
The type Foo can either be a Value Type or a Reference Type, except in Objective-C of course.
Assuming Foo is a reference type, then for C# and VB.NET the first line will not allocate any memory for the object were as the Objective-C first line will actually allocate the memory, so this is a difference. The .NET languages perform the allocation and initialization in one line in the second line.
In the case that Foo is a Value Type, then the .NET languages are analagous to each other, Objective-C does not have value types (at least not the last time I worked with it 15 years ago).
You're overwriting bar
in both C# and VB.NET. Your code is equivalent to just:
Foo bar; // does nothing but declare a handle
bar = new Foo(); // alloc AND init
or simply:
Foo bar=new Foo();
Where Obj-C apparently separates allocation from initialization, all other C++-like languages combine the 2, thinking (correctly imo) that you never want to have partially-uninitialized objects (constructors aside, of course).
精彩评论