C++/CLI:本机参考与跟踪参考
下面两个函数有什么区别?
ref class SomeClass;
void swap(SomeClass^& a, SomeClass^& b){
SomeClass^ c = a;
a = b;
b = c;
}
void swap2(SomeClass^% a, SomeClass^% b){
SomeClass^ c = a;
a = b;
b = c;
}
What is the difference between the following two functions?
ref class SomeClass;
void swap(SomeClass^& a, SomeClass^& b){
SomeClass^ c = a;
a = b;
b = c;
}
void swap2(SomeClass^% a, SomeClass^% b){
SomeClass^ c = a;
a = b;
b = c;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
引用和跟踪引用之间的主要区别在于,跟踪引用允许通过垃圾收集进行移动。
在 gc 运行期间,对象会四处移动。如果您在按地址移动对象后访问该对象,则会读取垃圾。这就是跟踪句柄发挥作用的地方。它知道 gc 及其对象的移动。移动后您仍然可以访问该对象。
来自 MSDN:
我不知道获取GC对象的引用(&)是否会阻止它被GC移动。
The main difference between a reference and a tracking reference is, that the tracking reference is allowed to be moved by the garbage collection.
During the run of the gc, objects are moved around. If you access an object after it is moved by it's adress, you read garbadge. That's where the tracking handle comes in. It is aware of the gc and its object moving. You can still access the object after it has been moved.
From MSDN:
I don't know if taking a reference (&) of an gc-object stops it from being moved by the gc.
我的猜测是,第二种情况不能从外部 C++/CLI(例如 VB、C# 等)使用,而第一种情况可以。不过我没有尝试过。
My guess is that the 2nd case cannot be used from outside C++/CLI (e.g., VB, C#, etc.), whilst the first can. I didn't try it, though.