Does new always allocate on the heap in C++ / C# / Java

后端 未结 9 1308
既然无缘
既然无缘 2020-12-28 08:58

My understanding has always been, regardless of C++ or C# or Java, that when we use the new keyword to create an object it allocates memory on the heap. I thou

相关标签:
9条回答
  • 2020-12-28 09:16

    In Java and C#, we don't need to allocate primitive types on the heap. They can be allocated on the stack ( not that they are restricted to stack ). Whereas, in C++ we can have primitive as well as user defined types to be allocated on both stack and heap.

    0 讨论(0)
  • 2020-12-28 09:18

    Java 7 does escape analysis to determine if an object can be allocated on the stack, according to http://download.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html.

    However, you cannot instruct the runtime to allocate an object on heap or on stack. It's done automatically.

    0 讨论(0)
  • 2020-12-28 09:24

    In c#, a class always lives on the heap. A struct can be either on the heap or stack:

    • variables (except captures and iterator blocks), and fields on a struct that is itself on the stack live on the stack
    • captures, iterator blocks, fields of something that is on the heap, and values in an array live on the heap, as do "boxed" values
    0 讨论(0)
提交回复
热议问题