C++: better to keep reference or pointer? -
this might regarded style question. have class keeps reference instance of class:
class { }; class b { a& ref; public: explicit b(a& ref) : a(ref) { } };
i decided use references instead of pointers, because ref never null pointer. also, code looks nicer.
but, user has no idea whether copy or not right? in case, don't copy, if destroyed while instance of b still existing, problems happen. if use pointers, of course same can happen, feel user aware, writes code, no copying being done.
opinions this? best c++ way deal problem?
ps.: 1 solution thought of make things pointer kept, if object points destroyed, copy made first. not difficult implement, point is: trouble worth , overhead justify it? sort of self-made reference counter people really?
if b
must ever use single instance of a
, instance never change, reference makes sense. thus, b
cannot constructed without instance of a
- introduce tight coupling.
however, if can have instance of b
independently of a
, make pointer - allow set instance of a
later needed. eitherway, have guarantee lifetime of a
; way avoid this(life time control) use smart pointer manage life time of a
.
Comments
Post a Comment