First difference between java and C++ is that all objects in java are either primitives or reference to other objects. C++ has one more called pointer which is actually analogous to java's reference objects.
As primitive variables in both C++ and Java are allocated on the stack, there is no need to have an explicit method of freeing the memory they contain as this is automatically done when the scope of the method the primitives are declared in, has finished.
However, java's automatic GC (garbage collector) counts references to an object and when this counter gets to zero, the object is now ready to be garbage collected. So when an object is allocated with the `new` keyword, it's reference counter is set the number of references pointing to the object. So if you initially declare an object:
1 2
|
String mystr = new String();
// reference count of mystr is 1 so this object is not garbage collected
|
Or this:
1 2 3
|
new String()
// reference count of this object is 0, so as soon as the constructor is
// finished, the object is garbage collected
|
In c++, there is no such thing as garbage collection, but as of c++11, smart_pointers were introduced to the language and these implement the reference counting of java gc.
http://en.cppreference.com/w/cpp/memory
@
Stewbond
In java function arguments are pass by value, but since the values are either primitives or references, this doesn't affect performance. So in your swap example, your swap function simply received variables of type `T` which is a copy of the reference to the actual objects you are working with. So your swapping has no effect on the original reference.