Let's look at an example that shows a disadvantage of having references as members of a class:
template <typename T>
A<T>::A(T & obj) : x(obj) {} // constructor (this would probably go in the header)
int main(void) {
int * num = new int;
*num = 42;
A<int> a(*num); // a.x references *num
delete num; // uh-oh, *num is no longer valid and a.x cannot rebind
return 0;
}
Of course, if the member variable was declared T x;
, then x
would be another instance of T
capable of storing a copy the data of *num
even after num
is deleted.