What is the best way to deal with a bunch of references in a class
I have a class that references a group of other classes. I want to be able to add these references gradually (i.e. not all at the same time in the constructor), and I want to prevent the ability to remove the underlying object of these references from my class, also I want to check for NULL-ness on these references. so I know that no specific link has been added. What is a good design to meet these requirements?
a source to share
I agree with other comments that you should be using boost::shared_ptr
.
However, if you don't want the class containing these references to partially control the lifetime of the objects it references, you should consider using it boost::weak_ptr
to store references, then turn that into shared_ptr
when you want us to. This will remove deleted objects in front of your class and you will always know if the object has been deleted before using it.
a source to share
It looks like you are trying to create a Service Locator .
As a side comment: I personally would recommend not doing this because it's going to make testing really, really hurt if you ever want to do it . Constructor injection (something you're trying to avoid) will make testing much easier.
a source to share
Despite all the recommendations that you use boost :; shared_pointer, it's far from obvious from your post that it would be advisable to do this, since the class has no property semantics. A regular C ++ pointer would be pretty good here.
At the end of the day, it is difficult to prevent the smart pointer from deleting because the smart pointer must in some form or another provide access to the main dumb pointer, which of course can always be deleted. For some problems, there is no technological solution, in which case code review is the best way to catch semantic errors when using contained pointers.