This might be regarded as a style question. I have a class that keeps a reference to an instance of another class:
class A { };
class B {
A& ref;
public:
explicit B(A& ref) : A(ref) { }
};
I decided to use references instead of pointers, because ref could never be a null pointer. Also, the code looks nicer.
But, the user has no idea whether I copy A or not right? In this case, I don't copy, so if A is destroyed while an instance of B is still existing, problems will happen. If you use pointers, then of course the same can happen, but I feel that the user is then aware, as he writes the code, that no copying is being done.
Opinions about this? What would be the best C++ way to deal with this problem?
PS.: One solution I thought of is to make things so that a pointer is kept, but if the object it points to is destroyed, then a copy is made first. This is not so difficult to implement, but the point is: would the extra trouble be worth it and would the overhead justify it? Is this sort of self-made reference counter something that people do really?