Sunday, November 16, 2003

Re: Allocation vs Initialization in Java/.NET

Yeah I'm pretty sure in Java it will be what you posted. But there is a slight difference. Since in Java all user defined classes are reference types that will always be created on the heap, that array of Foo's will hold only references, not objects. So the size of the array will be sizeof( reference ) * 10. That reference size will be dependant on the OS. If it is 32 bit, it will be 32 bits, if 64 bit, 64 etc... (Is this right? Can you verify about reference/pointer size?)

In .NET you have the ability to create objects that will be created on the stack...

struct SFoo {} // created on Stack (this is NOT the same as C++ struct)
class CFoo {} // created on Heap

So I guess here you could have it both ways...

SFoo sf[ 10 ]; // allocate space for 10 SFoos on stack
for ( int i = 0; i < 10; ++i )
sf[ i ] = new SFoo( 1, 2 ); // initialize SFoo

CFoo cf[ 10 ]; // allocate space for 10 CFoo references on stack
for ( int i = 0; i < 10; ++i )
cf[ i ] = new CFoo( 1, 2 ); // allocate and initialize CFoo on heap and return reference to it

About C++ struct vs C# struct. The only difference between struct and class in C++ is that by default everything is public in struct and everything is private in class. You can create structs on the heap and classes on the stack and of course vice-versa. In C#, you can only create structs on the stack and classes on the heap.

And don't worry... I'm going to be posting some real lame shit too. Point is that we can share some stuff and learn off of each other.

BTW, when you're at ORielly, I'll be expecting some of them cool T-Shirts.

No comments: