C++/CLI:本机参考与跟踪参考

发布于 2024-08-15 04:46:00 字数 251 浏览 4 评论 0原文

下面两个函数有什么区别?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哥,最终变帅啦 2024-08-22 04:46:00

引用和跟踪引用之间的主要区别在于,跟踪引用允许通过垃圾收集进行移动。

在 gc 运行期间,对象会四处移动。如果您在按地址移动对象后访问该对象,则会读取垃圾。这就是跟踪句柄发挥作用的地方。它知道 gc 及其对象的移动。移动后您仍然可以访问该对象。

来自 MSDN

跟踪参考类似于
C++ 参考,指定
变量通过以下方式传递给函数
参考并创建替代方案
对象的名称。然而,
跟踪引用的对象
参考可以在期间移动
通过通用语言执行
运行时垃圾收集器。

我不知道获取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:

A tracking reference is similar to a
C++ reference, to specify that a
variable is passed to a function by
reference and to create an alternative
name for an object. However, the
object referenced by a tracking
reference can be moved during
execution by the common language
runtime garbage collector.

I don't know if taking a reference (&) of an gc-object stops it from being moved by the gc.

迷荒 2024-08-22 04:46:00

我的猜测是,第二种情况不能从外部 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文