References themselves are unrelated to the issue.
The issue is because C++ manages object lifetimes differently from run-time systems that employ garbage collectors, such as Java.
There is no standard built-in garbage collector in C++.
Both automatic (within local or global scope) and manual (explicitly allocated/deallocated in heap) object lifetimes are possible in C++.
A C++ reference is nothing more than an object's alias.
It has no knowledge of object lifespan (for the sake of efficiency).
The coder must give it some thought.
A reference bound to a temporary object is an exception; in this situation, the temporary object's lifespan is prolonged to include the lifetime of the bound reference.
References play a crucial role in the fundamental ideas of C++, and they are required for 90% of jobs.
Otherwise, pointers must be used, which is typically far worse.
You can use references, for instance, when you need to give an object as a function parameter by reference rather than by value:
void f(A copyOfObj); ...READ MORE
Aug 5, 2022
in C++
by
Damon
• 4,960 points
•
641 views