简体   繁体   English

为什么在 Java 中对象是在堆上而不是在堆栈上创建的?

[英]Why are objects made on the heap and not on the stack in Java?

What was the reasoning behind this decision?这个决定背后的原因是什么? Why dynamically make objects on the heap and not on the stack?为什么动态地在堆上而不是在堆栈上创建对象? By doing it on the are we saving space?通过这样做,我们是否节省了空间?

If you allocate an object on the stack, its life time is limited to the current method call.如果你在栈上分配一个 object,它的生命周期被限制在当前的方法调用中。 When the method returns, the object is automatically destroyed, together with everything else stored in the stack frame.当该方法返回时,object 连同存储在堆栈帧中的所有其他内容一起被自动销毁。 This means it's impossible to write a function that returns an object, or a function that adds a new object to a list.这意味着不可能编写返回 object 的 function 或将新的 ZA669CFDE63131CC4BEB62268CFDE63191C1C1C425268E68385D1AB5074C17A94F14Z 添加到列表的 function。

You could make it work by copying or moving the object like c++ does.您可以通过复制移动object 来使其工作,就像 c++ 一样。 But then you have to deal with the complexity of C++.但是你必须处理 C++ 的复杂性。 Java was supposed to be simpler than that. Java 应该比这更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM