C#: Benefit of explicitly stating “unsafe” / compiler option

前端 未结 9 1717
执笔经年
执笔经年 2021-01-12 09:13

I understand pointers and the rare need to use them in C# code. My question is: what is the reasoning behind having to explicitly state \"unsafe\" in a block of code. Additi

9条回答
  •  有刺的猬
    2021-01-12 09:36

    The most significant difference between safe and unsafe code is that unsafe code is unreachable by .net's garbage collector. Automatic GC is a huge part of the vernacular of .net and, when you go beyond its boundaries, you change a lot of what can be assumed about your code.

    Pointers in particular allow for the creation of objects on the heap with no GC references. This leads to another excellent reason to require code to be marked as "unsafe." It makes it easy to narrow down where a memory leak is coming from when you realize you have one.

提交回复
热议问题