In Java, all variables containing proper objects are actually references (i.e. pointers). Therefore, method calls with these objects as arguments are always \"by reference\"
in Java, a reference is a garbage-collected "smart pointer".
C++ also uses the concept of smart pointers, which are in the
library, called unique_ptr
and shared_ptr
. shared_ptr is reference-counted so can be used in the same way as Java References. unique_ptr is similar, except is noncopyable and a little more lightweight. The benefit of both is never ever needing to use the delete keyword, and being able to rely on "pointers" which are protected by exceptions.
C++ also supports the concept of a reference - which is usually a good choice for passing objects around (And even better is reference-to-const). References in C++ are bound to the type of object which is passed, so you need to specify (using the reference symbol &
) in the function signature
#include
void foo(std::string& bar)
{
bar = "world";
}
void foo2(const std::string& bar)
{
//passed by reference, but not modifyable.
}
int main()
{
std::string str = "hello";
foo(str);
foo2(str);
}
As for "raw" pointers - you can nearly always avoid them by using either a smart pointer, a reference, an iterator, or pass-by-value. plain ordinary pointers come with a mixed bag of "gotchas" which C++ inherited from the C language - if you've got a fairly recent compiler you should never really need to use them at all (unless you're going to be doing things like re-inventing the wheel for learning purposes with memory management, data structures, etc.)