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

微笑、不失礼 提交于 2021-02-18 05:24:39

问题


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

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


回答1:


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

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.




回答2:


Everything for object creation is hidden behind the newobj opcode (or initobj for value-types). As such, it is entirely an implementation detail how and where memory is allocated, and how that ties into other memory management structures.



来源:https://stackoverflow.com/questions/11504910/what-does-the-new-keyword-in-net-actually-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!