As my first programming language I learned Java, but since I changed to a different University, I am now learning C++.
Coming from Java and learning the basics of C++, I read about references and reference variables. And how dangerous they can be, and how to be careful with them and so on.
So in my head arises one simple question:
Why should I bother using that kind of complicated, and therefore potentially problem-causing, stuff at all?
Is it somehow worth it, or just a relic from times where RAM was about 64MB big?
Since a lot of answers have mentioned pointers: That concept is clearly from the stone age, imho. Except for high-performance-computation I wouldn’t even touch that stuff.
The problem is not related to references itself.
The problem is that in C++, object lifetime is managed differently than in Java or other run-time environments that use a garbage collector. C++ doesn’t have standard built-in garbage collector. C++ object lifetime can be automatic (within local or global scope) or manual (explicitly allocated/deallocated in heap).
A C++ reference is just a simple alias for an object. It doesn’t know anything about object lifetime (for the sake of efficiency). The programmer must care about it. An exception is the special case where a reference is bound to a temporary object; in this case, the lifetime of the temporary is extended to lifetime of the bound reference. Details are here.
References are an important part of C++ basic concepts and you just cannot avoid using them for 90% of tasks. Otherwise you have to use pointers, which is usually even worse 🙂
E.g., when you need to pass object as function argument by reference instead of by value you can use references: