Dynamic Memory Allocation for References

rajagb4u's Avatar, Join Date: Aug 2010
Newbie Member
Hi,
I have a question regarding the references in C++.Can the references be allocated memory dynamically using malloc or new?
If yes,is it required to deallocate the memory at the end?

Prasanth
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Yes (assuming you mean "can a reference point to memory that is dynamically allocated").

If you allocate memory with new or malloc, it is ALWAYS required to balance that with free or delete.
0
LordN3mrod's Avatar, Join Date: Sep 2010
Go4Expert Member
T* p = new T;
T& r = *p;
///r is a reference to the dynamically allocated p here
delete p; //ok, freeing memory
r.dosomething;// undefined - the referent has been destroyed!