In Java, when I do
Foo bar = new Foo();
bar will be a variable containing the address of the newly constructed object. My professor call it a reference variable
The previous line is equivalent to this in C++:
Foo *bar = new Foo();
here, bar is a pointer to the object
So, is it true that a reference variable in Java is basically a pointer?
Also, when I do this in C++:
Foo bar;
is bar also a pointer? If not, then does that mean there is a difference in memory structure between
Foo bar;
and
Foo *bar = new Foo();
?
Pointers in C++ behave similarly to references in Java.
However,
Foo bar;is very different fromFoo *bar = new Foo();. The first creates an instance of Foo with automatic duration. It will be destroyed at the end of the block in which it is created. The second creates a dynamically allocated instance of Foo. It will stick around until it is explicitly deleted.The first can’t be used if you want the object to exist after the function returns. If you use a pointer or a reference to it after the function returns, bad things will happen. In that situation, you have to use the second form.
The advantage of the first form is that you don’t have to worry about memory management. It will be automatically destroyed at the end of its scope. With the second form, you have to manually delete it, or manage it with a smart pointer of some kind.