简体   繁体   中英

memory allocation - Java vs C++

Given class Line in both java and C++, and the following declarations in java and C++ respectively -

Line[] p; 

and

Line *p;

What are the differences in semantics between the two languages when then running the following code:

p = new Line[7];

In particular, do both languages assign heap memory for the array in the same way?

Sorry I done research on this matter, however i still feel i have not completely understood.

Thanks!

You're comparing Java and C++ code that is not equivalent. The following C++ is the equivalent of your Java code (array of references):

Line **p;
p = new Line*[7];

The C++ version you posted:

Line *p;
p = new Line[7];

is an array of objects and initializes each element of the array using the default constructor of 'Line' (try it with an explicit 1-parameter constructor and you'll see that C++ tells you that you need a default constructor). Java has no equivalent to this way of creating arrays of non-primitive types that get each element default-constructed - in Java all elements of a non-primitive type array are 'null' until you explicitly assign them).

When arrays are declared in Java, they are stored as an array of references. You wouldn't run into this overhead cost when initializing an array of the Line class in C++ because your array will hold the objects, not merely their references.

As said above, the equivilant C++ code is actually

Line **p;
p = new Line*[7];

since Java allocate an array of references, not array of ad-hoc objects.

In C++, the new operator is guarenteed to allocat memory from the heap. In Java - it depends. usually the new keyword allocate memory from the heap, but some compilers, such as HotSpot preform what is called "escape analysis" : if the compiler detects that a pointer is not returned from a function, nor going to different thread - it may declare the object in the stack (equivilant to Line p[7] C++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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