Click here to Skip to main content
16,013,082 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
what is the difference between java reference and c++ reference?
i google this but found nothing!
Posted
Comments
Sergey Alexandrovich Kryukov 11-Jun-12 10:47am    
Do you mean C++ or C++/CLI where there are referenced, or unmanaged pointers? In native C++, the references are pretty much unrelated to pointers. Java references are more like C++ pointers, but they are "managed", pretty much like in .NET.
--SA

In C++ references are just an alias for an object. They can only ever refer to a single object which is set when the reference is initialised.

Java references are like std::shared_ptr in C++. They can only ever refer to one object at a time but they can be rebound. They also give a lower bound for the lifetime of the object - as long as there's one reference to the object the object won't be garbage collected.

So to sum up:

- C++ references are bound to the same object for the lifetime of the reference and don't play any part in controlling the lifetime of the object.[1]

- Java references are bound to one object at a time but can be assigned other objects while the program executes. If any reference exists to an object it won't be garbage collected, unlike in C++ where having a reference to an object doesn't mean that the object's alive.

[1] with one exception - a const reference to a temporary object keeps the temporary object alive for as long as the reference is alive.
 
Share this answer
 
v2
Comments
Reza Oruji 11-Jun-12 14:38pm    
could you please give me a link to read about std pointers?
Manas Bhardwaj 12-Jun-12 2:07am    
correct +5!
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 11-Jun-12 10:53am    
Come one, you link to the same page. Format the link properly, to start with.
--SA
Richard MacCutchan 11-Jun-12 12:34pm    
Fixed your link. Please check what you have posted before publishing.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Jun-12 10:52am    
The answers address the questions asked on the referenced page formally, but do not explain essential features of Java references, which is impossible without explaining garbage collection and related topics. I voted 4.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900