简体   繁体   中英

Java c++ Reference question

In c++ we use & to represent pass by reference. Since objects are always passed by reference you do not need to use this &? Or does it not matter?

How do java and c++ differ in pass by value and reference. Everything in java I thought is pass by reference but it is pass by value? Why is this? So is it primitives are pass by value while class objects are pass by reference?

Clear two things up:

  1. C++ default is pass by value always , and you explicitly have to indicate if your function accepts a reference with the &
  2. Java is pass by value always (objects are not passed by reference, but the reference is passed by value - ie it's a copy of the reference to the object - hence you can modify the object using that reference but you can't expect operations like swaps[one reference with another] to work correctly)

I wrote a detailed answer before on the C++ argument passing semantics that include a final section on how Java semantics differ. You can read it here

Basically, and taking arrays aside (more on arrays here ), as those are a different beast. In C++ if the argument type does not contain & it is passed by value (copied). If the type contains a * then it is a pointer, and it is the pointer the one that gets copied, but a copy is performed.

In Java, with reference types you never work with the actual object but with references to it (pointers in C/C++ dialect). All arguments are passed by value, which means that the reference will get copied (the function will not be able to modify the caller's reference) but the referred object can be modified through the copied reference.

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