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

后端 未结 9 1309
既然无缘
既然无缘 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:15

    I don't know precisely about Java (and it seems quite difficult to get a documentation about it).

    In C#, new invokes the constructor and returns a fresh object. If it is of value type, it is allocated on the stack (eg. local variable) or on the heap (eg. boxed object, member of a reference type object). If it is of reference type, it always goes on the heap and is managed by the garbage collector. See http://msdn.microsoft.com/en-us/library/fa0ab757(v=vs.80).aspx for more details.

    In C++, a "new expression" returns a pointer to an object with dynamic storage duration (ie. that you must destroy yourself). There is no mention of heap (with this meaning) in the C++ standard, and the mechanism through which such an object is obtained is implementation defined.

提交回复
热议问题