Home >Java >javaTutorial >Comparison of object placement arrangements in Java and C++

Comparison of object placement arrangements in Java and C++

黄舟
黄舟Original
2017-09-23 09:49:301257browse

This article mainly introduces relevant information on the comparison of the placement arrangements of objects in Java and C++. I hope this article can help everyone. Friends in need can refer to

Java Comparison of the placement arrangement of objects and objects in C++

Summary:

In Java, all objects are stored in the heap (Heap, a general memory pool); and References to objects are stored on the stack.
We can understand the relationship between objects and references and their storage locations by comparing the string directly declared by String and the string declared by new String using equals() and "==".

The stack is a fast and efficient method of allocating storage, second only to registers. When creating a program, the Java system must know the exact lifetime of all items stored within the stack in order to move the stack pointer up and down.

The advantage of a heap different from a stack is that the compiler does not need to know how long the data stored in the heap survives. Therefore, the heap is more flexible than the stack.
The stack in Java cannot be simply understood as the stack in the data structure, although they are all Stack in English. The stack in Java is located in general-purpose RAM (Random Access Memory), but has direct support from the processor through the stack pointer. If the stack pointer moves downward, new memory is allocated; if it moves upward, that memory is released.

For specific Java memory allocation, please see page P22 of "Thinking in Java".

In C++: As long as the objects declared using the new and malloc keywords are stored in the heap, the malloc keyword also operates on the heap memory:


A a(1);//栈中分配 
A b = A(1);//栈中分配 
A *c = new A(1);//堆中分配内存空间,将在堆中所创建的对象存储地址赋值给c指针 
A *d = (A*)malloc(sizeof(A));//堆中分配内存空间 
delete c;

The above is the detailed content of Comparison of object placement arrangements in Java and C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn