c# structs/classes stack/heap control?

前端 未结 5 928
醉梦人生
醉梦人生 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:30

    Don't be fooled by the new keyword, it's optional for structs.

    In C# there is a managed world where you enjoy the Garbage collector and Type-Safety and don't (have to) worry about many memory details. The Stack/Heap difference is irrelevant, it's about copy-semantics.

    For those rare cases where you do want control, there is the unsafe (unmanaged) part of C# with real pointers and everything.

    But the cost of things are different in C# than they are in C++ so don't hunt ghosts, unmanaged, short lived objects are very cheap. And the compiler can allocate small arrays on the stack as an optimization, you won't be able to tell and neither should you care.

提交回复
热议问题