基本上,问题在于编译器如何管理内存。
double[] b = {1.0, 2.0, 3.0};
double[] a = new double[3]; //for Java
double a[3]; //for C++
a = b;
当声明数组a
时,24字节的内存空间被分配给数组a
。
a=b
只是将数组b
的引用值 复制到a
。
那24字节的内存块呢?它会立即被释放,还是在函数/方法结束时被回收?
最佳答案
When array a is declared, 24 bytes memory space are assigned to array a.
在 C++ 中。在 Java 中,仅在声明中分配引用,而数组本身在初始化程序中分配。
a=b simply copies the value of the reference of array b to a.
在 java 。在 C++ 中,它不是合法代码。
What about the 24 bytes memory block? It will be deallocated immediately, or reclaimed by the end of the function/method?
在 C++ 中,它与封闭范围或更可能是封闭方法一起消失。在 Java 中,当对它的最后一个引用消失时,它就符合垃圾回收条件,在本例中是方法结束。
你的问题真的太困惑了,真的比那更有意义。尝试一次用一种语言思考。
关于java - 数组如何在 C++ 或 Java 中为 "copied",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22961065/