简体   繁体   English

理解C ++ .Net中的String ^

[英]understanding String^ in C++ .Net

I remember seeing somewhere there "^" operator is used as a pointer operator in Managed C++ code. 我记得在某处看到“^”运算符用作托管C ++代码中的指针运算符。 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: 假设我的理解是对的,当我开始理解.Net并编写了一些示例程序时,我遇到了一些这样的代码:

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 . String^是指向托管堆的指针,也就是句柄 Pointers and handles are not interchangable. 指针和手柄不可互换。

Calling new will allocate an object on an unmanaged heap and return a pointer. 调用new将在非托管堆上分配对象并返回指针。 On the other hand, calling gcnew will allocate an object on a managed heap and return a handle. 另一方面,调用gcnew将在托管堆上分配一个对象并返回一个句柄。

The line username = "XYZ" is merely a compiler sugar. username = "XYZ"仅仅是编译器糖。 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. 当没有任何内容再次引用时,它将自动分配和释放。

如果您认为^shared_ptr类似,那么您将与事实相去甚远。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM