Why should I use reference variables at all? [closed]

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:

void f(A copyOfObj);       // Passed by value, f receives copy of passed A instance
void f(A& refToObj);       // Passed by ref, f receives passed A instance itself, modifiable
void f(const A& refToObj); // Passed by const ref, f receives passed A instance itself, non modifiable

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)