简体   繁体   English

.net中的“new”关键字实际上做了什么?

[英]What does the “new ” keyword in .net actually do?

I know that the new keyword is calling the class constructor but at which stage do we allocate memory for the class? 我知道new关键字正在调用类构造函数,但是我们在哪个阶段为类分配内存?

In my understanding it should correspond to the GCHandle.Alloc(Object) method but I'm unable to find the connection. 根据我的理解,它应该对应于GCHandle.Alloc(Object)方法,但我无法找到连接。

The new operator is implemented in the CLR. 运算符在CLR中实现。 It allocates memory from the garbage collected heap and executes the class constructor. 它从垃圾收集堆中分配内存并执行类构造函数。

GCHandle.Alloc() is not the same. GCHandle.Alloc() 一样。 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. 这利用了GC中的单独机制来创建对对象的引用,存储在单独的表中的引用以及除了在垃圾收集期间通常找到的对象引用之外还要进行扫描。 You must pass Alloc() an existing object reference, it adds another. 您必须传递Alloc()一个现有的对象引用,它会添加另一个。 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. C ++ / CLI中的gcroot <>模板类利用它。

Everything for object creation is hidden behind the newobj opcode (or initobj for value-types). 用于创建对象的所有内容都隐藏在newobj操作码(或用于值类型的initobj )之后。 As such, it is entirely an implementation detail how and where memory is allocated, and how that ties into other memory management structures. 因此,它完全是一个实现细节 ,分配内存的方式和位置,以及它与其他内存管理结构的关系。

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

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