Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding String^ in C++ .Net

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.

like image 413
FatDaemon Avatar asked Jul 14 '09 20:07

FatDaemon


3 Answers

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");
like image 52
avakar Avatar answered Sep 29 '22 06:09

avakar


That's a reference, not pointer, to a garbage collected string.

It will be allocated and deallocated automatically, when nothing is referencing it anymore.

like image 32
GManNickG Avatar answered Sep 29 '22 08:09

GManNickG


If you consider that ^ is similar to shared_ptr you will be not far from the truth.

like image 37
Kirill V. Lyadvinsky Avatar answered Sep 29 '22 06:09

Kirill V. Lyadvinsky