-1

What are the disadvantages of defining a field (in a class) as a reference?
For example:

template <typename T>
class A {  
    T& x; 
public:  
    //....
}

In addition, are there special things that I need to do while I define a reference member?

Holt
  • 36,600
  • 7
  • 92
  • 139
AskMath
  • 415
  • 1
  • 4
  • 11
  • 1
    Why are you asking? What is the actual problem you have? Or it it just curiosity? Did you see something like that in some other code? And what do *you* think some possibly disadvantages could be? – Some programmer dude Jun 27 '18 at 16:27

1 Answers1

-2

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.

jdc
  • 680
  • 1
  • 8
  • 11