C++/CLI中见过这个符号:^
C++中我们用*来表示一个指针,在C++/CLI中,我们用符号^来表示句柄。
现在*用来指定CRT heap上的原生指针,而句柄是安全指针,它位于托管堆上。
你可以把句柄当成引用来考虑,和原生指针不同的是,他们不会引起内存泄漏,即便没有对它们进行适当的删除,因为GC会处理这些问题,并且他们没有一个固定的内存地址,所以在执行的时候它们会被移来移去。
%对于^就相当于&对于*
N* pn = new N;//分配在原生heap上 n& rn = *pn;//绑定一个普通引用到原生对象 R^ hr = gcnew R;//分配在CLI heap上 r% rr = *hr;//绑定跟踪的引用到gc-lvalue
一 在VS2017/2019 安装 C++/CLI的模块支持




二 新建C++/CLI项目

三 添加源文件


String^ fileName = "textfile.txt"; StreamWriter^ sw = gcnew StreamWriter(fileName);
If you use the sample program, notice thatyou use the
gcnewkeyword instead ofnewwhen creating a.NET object,and thatgcnew returnsa handle( ^ )rather than a pointer( * ):
using namespace System;
using namespace System::IO;
int main()
{
String^ fileName = "textfile.txt";
StreamWriter^ sw = gcnew StreamWriter(fileName);
sw->WriteLine("Hi Major");
sw->Close();
Console::WriteLine("a new file ('{0}') has been written", fileName);
return 0;
}




声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)