I remember seeing somewhere there "^" operator is used as a pointer operator in Managed C++ code. Hence "^" should be equivalent to "*" operator right??
Assuming my understanding is right, when I started understanding .Net and coded a few example programs, I came across some code like this:
String ^username; //my understanding is you are creating a pointer to string obj
.
. // there is no malloc or new that allocates memory to username pointer
.
username = "XYZ"; // shouldn't you be doing a malloc first??? isn't it null pointer
I am having trouble understanding this.
String^
is a pointer to the managed heap, aka handle. Pointers and handles are not interchangable.
Calling new
will allocate an object on an unmanaged heap and return a pointer. On the other hand, calling gcnew
will allocate an object on a managed heap and return a handle.
The line username = "XYZ"
is merely a compiler sugar. It is equivalent to
username = gcnew String(L"XYZ");
That's a reference, not pointer, to a garbage collected string.
It will be allocated and deallocated automatically, when nothing is referencing it anymore.
If you consider that ^
is similar to shared_ptr
you will be not far from the truth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With