Couple of questions on Handles

  • Thread starter Thread starter Jack
  • Start date Start date
J

Jack

So I am learning c++/cli and I have a couple of questions about
handles. From what I understand these two are pretty similar except
that handles point to Managed Heap and Pointer point to the native
heap. My question is in the following code where is the handle
pointing to?

int^ handle = 5;

is this on the managed heap? and what is the diff between the above
and this:

int^ handle = gcnew int;
handle = 5;

Are they both the same? if so then what is the point of using the
gcnew keyword. Also does a handle (similar to a pointer) holds the
memory address of the item? If so then why can't u do something like
this?

int a = 6;
int^ handle = &a;

and lastly, since we can use things like realloc and calloc in C, are
their similar functions for handles?

Thanks
Jack
 
Jack said:
So I am learning c++/cli and I have a couple of questions about
handles. From what I understand these two are pretty similar except
that handles point to Managed Heap and Pointer point to the native
heap. My question is in the following code where is the handle
pointing to?

int^ handle = 5;

is this on the managed heap?

That's correct. This is called "implicit boxing". The number 5 is allocated on the managed heap as an Object of type System::Int32.


and what is the diff between the above
and this:

int^ handle = gcnew int;
handle = 5;

They are the same.

Are they both the same? if so then what is the point of using the
gcnew keyword. Also does a handle (similar to a pointer) holds the
memory address of the item?

It holds a "reference". Remember, the garbage collector is free to move the objects around on the managed heap at any time in order
to make room, so the address of those objects becomes somewhat meaningless. But it should be clear to you now why we distinguish
int^ from int*.

If so then why can't u do something like
this?

int a = 6;
int^ handle = &a;

Implicit boxing can handle the boxing of integers, but not the boxing of addresses, so the above is illegal.
and lastly, since we can use things like realloc and calloc in C, are
their similar functions for handles?

No, not really.

Brian
 
Back
Top