c# structs/classes stack/heap control?

前端 未结 5 872
醉梦人生
醉梦人生 2021-02-01 09:02

so in c++ it\'s very easy. you want whatever class/struct to be allocated on the heap, use new. if you want it on the stack, don\'t use new.

in C# we always use the new

5条回答
  •  星月不相逢
    2021-02-01 09:26

    While in the general case it's true that objects are always allocated on the heap, C# does let you drop down to the pointer level for heavy interop or for very high performance critical code.

    In unsafe blocks, you can use stackalloc to allocate objects on the stack and use them as pointers.

    To quote their example:

    // cs_keyword_stackalloc.cs
    // compile with: /unsafe
    using System; 
    
    class Test
    {
       public static unsafe void Main() 
       {
          int* fib = stackalloc int[100];
          int* p = fib;
          *p++ = *p++ = 1;
          for (int i=2; i<100; ++i, ++p)
             *p = p[-1] + p[-2];
          for (int i=0; i<10; ++i)
             Console.WriteLine (fib[i]);
       }
    }
    

    Note however that you don't need to declare an entire method unsafe, you can just use an unsafe {...} block for it.

提交回复
热议问题