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

前端 未结 2 1604
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 10:47

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 correspon

2条回答
  •  余生分开走
    2021-02-14 11:18

    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.

提交回复
热议问题