“新"是什么?.net中的关键字实际上是做什么的? [英] What does the "new " keyword in .net actually do?

查看:45
本文介绍了“新"是什么?.net中的关键字实际上是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 new 关键字正在调用类构造函数,但是我们在哪个阶段为该类分配内存?

I know that the new keyword is calling the class constructor but at which stage do we allocate memory for the class?

据我所知,它应该对应于 GCHandle.Alloc(Object)方法,但是我找不到连接.

In my understanding it should correspond to the GCHandle.Alloc(Object) method but I'm unable to find the connection.

推荐答案

new 运算符在CLR中实现.它从垃圾回收堆中分配内存,并执行类构造函数.

The new operator is implemented in the CLR. It allocates memory from the garbage collected heap and executes the class constructor.

GCHandle.Alloc()不相同.这利用了GC中的独立机制来创建对对象的引用,这些引用除了在垃圾回收期间通常找到的对象引用之外,还存储在单独的表中并进行了扫描.您必须传递Alloc()一个现有的对象引用,它添加另一个.对于创建弱引用和固定引用很有用,并且一种允许非托管代码存储对托管对象的引用并使它保持活动状态的机制.C ++/CLI中的 gcroot<>模板类可以利用它.

GCHandle.Alloc() is not the same. That takes advantage of a separate mechanism in the GC to create references to objects, references that are stored in a separate table and scanned in addition to object references found normally during a garbage collection. You must pass Alloc() an existing object reference, it adds another. Useful to create weak and pinning references and a mechanism to allow unmanaged code to store a reference to a managed object and keep it alive. The gcroot<> template class in C++/CLI takes advantage of it.

这篇关于“新"是什么?.net中的关键字实际上是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆