I have a class that references a bunch of other classes. I want to be able to add these references incrementally (i.e. not all at the same time on the constructor), and I want to disallow the ability to delete the object underlying these references from my class, also I want to test for NULL-ness on these references so I know a particular reference has not been added. What is a good design to accomplish these requirements?
It sounds like you might be trying to build a Service Locator.
As a side-comment: I would personally recommend not doing that, because it is going to make testing really, really painful if you ever want to do it. Constructor injection (Something that you are trying to avoid) will make testing much easier.
I agree with other comments that you should use boost::shared_ptr
.
However if you don't want the class holding these references to part-control the lifetime of the objects it references you should consider using boost::weak_ptr
to hold the references then turn this into a shared_ptr
when you want to us it. This will allow the referenced objects to be deleted before your class, and you will always know if object has been deleted before using it.
Despite all the recommendations that you use boost:;shared_pointer, it is far from obvious from your post that it would be appropriate to do so, as the class appears to have no ownership semantics. An ordinary C++ pointer will do just fine here.
It is difficult at the end of the day to prevent deletion via smart pointer, as the smart pointer must, in some form or other, provide access to the underlying dumb pointer, which of course can always be deleted. For some problems there is no technological solution, and in this case a code review is the best way to detect semantic errors in using the contained pointers.
The object you want to reference could be derived from with something like this. That would prevent you from deleting them.
class T class NonDeletable : public T { private: void operator delete(void*); };