I have read lots of materials about parameter passings. But still I have a few little questions to ask. I understand how primitive types works, and right now I only care about passing objects as parameters.

Facts:

  1. Everything(primitives/objects) in Java is pass-by-value
  2. When an object is passed as a parameter in Java, the value of the reference variable is copied and passed. Therefore, any change to the object will be visible when the function exits.
  3. In C++, parameter passings could be done in three ways: call-by-value, call-by-pointer and call-by-reference.
  4. When an object pointer is passed as a parameter by call-by-pointer, the address of the object(the pointer) is copied and passed. The change will also reflects.

My guess:

Java's pass-by-value has the same effects as C++'s call-by-pointers for class objects? Am I right?

有帮助吗?

解决方案

You are right that the functionality of a Java object reference is basically identical to a C++ pointer except in C++ you can dereference and actually overwrite the memory block the pointer points to. You can't do that in Java.

So a Java object reference is like a C++ pointer but there is no * operator. The Java . operator is only for member access, like the C++ -> operator.

其他提示

Some corrections:

1) Everything(primitives/objects) in Java is pass-by-value

Yes, but "objects" is not within "everything". "Objects" are not values in Java. The only types in Java are primitive types and reference types, so the only values in Java are primitives and references (pointers to objects). Not "objects".

2) When an object is passed as a parameter in Java,

As above, an "object" is not a value in Java, and cannot be "passed". So this sentence doesn't make sense.

Your conclusions are right. Since references in Java are pointers to objects, they work the same way as pointers to objects in C++.

Everything(primitives/objects) in Java is pass-by-value When an object is passed as a parameter in Java, the value of the reference variable is copied and passed. Therefore, any change to the object will be visible when the function exits.

Everything in Java is passed by "value" by default, but the "value" that is passed is effectively the pointer (if you think of everything in Java as a pointer - the exception to this being primitives).

In C++, parameter passings could be done in three ways: call-by-value, call-by-pointer and call-by-reference. Java's pass-by-value has the same effects as C++'s call-by-pointers for class objects?

It is usually referred to as pass-by-value, pass-by-reference, pass-by-const-reference (in C++). Passing by pointer is just another way to pass-by-value (you are passing the pointer by value, but what the pointer points to effectively by reference) - this is effectively what Java does. If you change the pointer value, it is not reflected outside the function, but if you change the data that is being pointed to, it is (example)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top